node.js event
2018-12-30 00:00:00 +0000이벤트
javascript 이벤트 연결
- 아래 예제에서 load를 ‘이벤트 이름’ or ‘이벤트 타입’이라고 부름
- 매개변수로 입력한 함수를 ‘이벤트 리스너’ or ‘이벤트 핸들러’라고 부름
<script>
// window 객체에 load 이벤트를 연결
window.addEventListener('load', function(){
});
</script>
이벤트 연결
- node.js에서 addEventListener함수를 사용하거나 on함수를 사용하면 이벤트 연결이 된다 | 메서드 이름 | 설명 | |:——–:|:——–:| | on(eventName, eventHandler) | 이벤트를 연결 |
- process에 exit 이벤트를 연결했으므로 프로그램이 종료되면 ‘안녕히가세요’라는 단어를 출력한다
// process 객체에 exit 이벤트를 연겷
process.on('exit', function(code){
console.log("안녕히가세요");
});
- 만약 이벤트 연결을 10번 초과하면 에러가 난다(process.on(exit, function(){}) 을 11번 복사)
(node:4396) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 exit listeners added. Use emitter.setMaxListeners() to increase limit
- 이벤트 리스너 개수가 10번 넘어가는 건 빈번하므로 개수를 수정해야한다
- process.setMaxListeners함수를 사용해서 이벤트연결 최대개수를 수정하면 에러가 사라진다 | 메서드 이름 | 설명 | |:——–:|:——–:| | setMaxListeners(limit) | 이벤트 리스너 연결 개수를 조절 |
이벤트 제거
| 메서드 이름 | 설명 | |:——–:|:——–:| | removeListener(eventName, handler) | 특정이벤트의 이벤트 리스너를 제거 | | removeAllListeners([eventName]) | 모든 이벤트 리스너를 제거 |
var onUncaughtException = function(error){
console.log('예외가 발생했다 삭제하자');
// 이벤트 제거
process.removeListener('onUncaughtException', onUncaughtException);
};
// process 객체에 onUncaughtException 이벤트를 연결
process.on('uncaughtException', onUncaughtException);
// 2초 간격으로 예외를 발생시킴
var test = function(){
setTimeout(test, 2000);
error.error.error();
};
setTimeout(test, 2000);
이벤트 강제 발생
| 메서드 이름 | 설명 | |:——–:|:——–:| | emit(event, [arg1], [arg2]) | 이벤트를 강제로 실행 |
- 프로그램 종료 시에도 이벤트 리스너만 실행된다
process.on('exit', function(code){
console.log('안녕히 계세요..!');
});
// 이벤트를 강제로 발생
process.emit('exit');
process.emit('exit');
process.emit('exit');
process.emit('exit');
// 프로그램 실행중
console.log('프로그램 실행 중');
jdbc
2018-12-29 00:00:00 +0000이클립스에 데이터베이스 연동하기
- JDBC 드라이브 설치
- C:\oraclexe\app\oracle\product\11.2.0\server\jdbc\lib
- ojbc6 파일 copy
- Tomcat 8의 lib 폴더에 ojbc 붙여넣기
- 프로젝트에서 라이브러리에서 ojbc가 들어있는 것을 확인할 수 있음
오라클 접속 확인
- 접속
- 에러발생(오라클 서비스가 중지되어있어서 oracle 붙은 이름의 서비스는 실행시켜줌)
The Network Adapter could not establish the connection
이클립스-오라클 접속
- jdbc 로드
import java.sql.*;
Class.forName("oracle.jdbc.driver.OracleDriver");
- 데이터베이스 연결 객체인 Connection 생성
Connection con = null;
con=DriverManager.getConnection(url, uid, pwd);
- Statement 객체 생성하기
Statement stmt = con.createStatement( );
- SQL문을 실행하여 결과 처리
- ResultSet에 데이터가 저장되어있음
String str = "select * from member";
ResultSet rs = stmt.executeQuery(str);
- DAO : CRUD
- DTO : 테이블정보
- query 실행 시 에러 발생
- java.sql.SQLSyntaxErrorException: ORA-00917: missing comma
- 값에 콤마를 안찍어서 발생
Debuging
한줄한줄 내려가고 싶다: f6 해당 메소드에 들어가고싶다:f5
DBCP(DB Connection Pool)
- db query 요청할 때 마다 connect을 하면 많은 리소스를 잡아먹는다
- resource tag를 통해 DataSource를 얻음
- DataSource객체 안에 Connection Pool이 있다
- ‘server.xml’에서 Context 태그 사이에 DataResource 태그 추가
<Context docBase="JSP" path="/JSP" reloadable="true" source="org.eclipse.jst.jee.server:JSP">
<Resource auth="Container" driverClassName="oracle.jdbc.driver.OracleDriver" maxActive="100" maxIdle="30" maxWait="10000" name="jdbc/oracle" password="1234" type="javax.sql.DataSource" url="jdbc:oracle:thin:@localhost:1521:XE" username="kosta192"/>
</Context>
</Host>
- Connection을 java source code로 가져온다
- name으로 DataSource를 찾고, DataSource 안에 Connection을 가져온다
// DBCP방식으로 Connection객체 구하기
public Connection getConnection(){
DataSource ds = null;
try {
// server.xml에서 데이터리소스를 가져옴
Context ctx = new InitialContext();
ds = (DataSource)ctx.lookup("java:comp/env/jdbc/oracle");// jndi: name을 통해 리소스를 얻어옴.name이 jdbc/oracle
return ds.getConnection();
} catch (Exception e) {
// TODO: handle exception
}
return null;
}
- 결과 데이터를 가져오는 함수를 만든다
- 함수를 호출해서 Connection을 가져온다
public List<Board> listBoard(){
Connection conn = null;
try {
conn = getConnection();
System.out.println("conn:"+conn);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
- jsp에서 데이터를 가져오는 함수 호출
<%@page import="kosta.bean.BoardDao" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
BoardDao dao = BoardDao.getInsance();
dao.listBoard();
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
</body>
</html>
<h3>글목록 보기</h3>
<a href="insert_form.jsp">글쓰기</a>
<table width="500" border="1" cellpadding='0' cellspacing='0'>
<tr>
<td>글번호</td>
<td>제목</td>
<td>작성자</td>
<td>작성일</td>
<td>조회수</td>
</tr>
<%
for(int i = 0; i < list.size(); ++i){
Board board = list.get(i);
}
%>
<tr>
<td><%= board.getSeq() %></td>
<td><%= board.getTitle() %></td>
<td><%= board.getWriter() %></td>
<td><%= board.getRegdate() %></td>
<td><%= board.getHitCount() %></td>
</tr>
<%}%>
</table>
자바빈
2018-12-28 00:00:00 +0000내장객체 Scope
- 아래 4개의 태그는 request, response 객체를 가짐. 범위를 가짐
- page : pageContext에 저장. 하나의 페이지까지
- request : HttpServletRequest에 저장. 내가 요청하는 페이지까지
- session : HttpSession에 저장. 세션이 만료될 때 까지
- application : ServletContext에 저장. 어플리케이션이 유지될 때 까지
JSP 객체 생성
- 자바 new 처럼 객체를 생성할 수 있다
- id명으로 객체를 접근할 수 있다
// jsp
<jsp:useBean id=“connection” class=“myapp.Connection” />
// java
myapp.Connection connection = new myapp.Connection();
//jsp
<jsp:useBean id=“connection” class=“myapp.Connection” >
<jsp:setProperty name=“connection” property=“timeout” value=“33”/>
</jsp:useBean>
// java
myapp.Connection connection = new myapp.Connection();
connection.setTimeout(“33”);
JSP 객체 사용 예제
- 아래 예제는 ‘insert_form.jsp’에서 여러 데이터(writer, title, contents)를 ‘insertAction.jsp’로 전송한다
- 이 때 getParameter를 사용하면 하나의 필드 당 하나의 값만 가져올 수 있어서 파라메터가 많아지면 비효율
- 간편하게 초기화할 수 있는 내장객체를 생성한다
- class의 생성자, set, get 메소드를 전부 만들어야 한다. 왜냐하면 값 생성 및 접근을 하기 위해서이다(만약 해당 함수가 없다면 값을 넣고, 가져오지 못해서 null로 출력된다)
- 해당 컴포넌트의 name과 class 필드의 name을 맞춰줘야 한다. 안맞추면 값 매칭이 안됨
- jsp:setProperty 태그에서 property의 값을 *으로 주면 모든 객체를 가져온다는 뜻이라서 일일이 필드 초기화 x
-
jsp:setProperty 태그의 name필드는 생성한 id값과 매칭된다
- insert_form.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
<h3>글쓰기</h3>
<hr>
<form action="insertAction.jsp" method="post">
작성자 : <input type="text" name="writer">
제목 : <input type="text" name="title">
내용
<textarea rows="6" cols="70" name="contents"></textarea>
<input type="submit" value="등록">
</form>
</body>
</html>
- insertAction.jsp
<%@ page import="kosta.bean.BoardDao" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
// usebean하기전 항상 인코딩 먼저해야한다!
request.setCharacterEncoding("utf-8");
%>
<!-- 객체 생성 -->
<jsp:useBean id="board" class="kosta.bean.Board" />
<!-- name은 id를 넣어주므로 board이다 -->
<!-- * form에서 넘어오는 값을 전부 초기화해준다 request.getParameter할 필요가 없다 -->
<!-- 필드에 set 메소드가 있어서 가능 -->
<jsp:setProperty property="*" name="board"/>
<%
BoardDao dao = BoardDao.getInsance();
dao.insertBoard(board);
%>
</body>
</html>
- Board.java
public class Board {
private String writer;
private String title;
private String contents;
public Board(){}
public Board(String writer, String title, String contents) {
super();
this.writer = writer;
this.title = title;
this.contents = contents;
}
@Override
public String toString() {
return "Board [writer=" + writer + ", title=" + title + ", contents=" + contents + "]";
}
public String getWriter() {
return writer;
}
public void setWriter(String writer) {
this.writer = writer;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContents() {
return contents;
}
public void setContents(String contents) {
this.contents = contents;
}
}
- BoardDao.java
public class BoardDao {
private static final BoardDao dao = new BoardDao();
public static BoardDao getInsance(){
return dao;
}
public void insertBoard(Board board){
System.out.println(board);
}
}
jsp, servlet 정리
2018-12-27 00:00:00 +0000JSP, Servlet 설정, 사용법
톰켓설정
- JavaEE 설정
- Window-Preperence 메뉴 클릭
- Server-Runtime Environments 메뉴에서 톰캣버전 설정, 톰켓 폴더 설정
- propertis-Project Facets-Runtimes에서 톰캣 체크.그러면 톰켓 lib가 추가됨
톰켓 라이브러리 추가
- 프로젝트 선택 후 오른쪽 마우스 클릭-Properties
- Project Facets-Runtimes
- Apach Tomcat 체크하고 Apply
인코딩 설정
- Web-HTML Files - Encoding UTF-8
- Web-JSP Files - Encoding UTF-8
프로젝트 생성
- Dynamic Project 만들 때 XML 생성체크하기
- (NEXT, NEXT 클릭하면 XML 생성 체크박스 있음)
웹 어플리케이션
- 웹을 기반으로 실행되는 프로그램
- 단순 화면을 출력하는게 아니라, 어떤 동작에 대한 처리를 한다(WAS:Web Application Server)
- Servlet과 JSP는 J2EE를 구성하는 기술 중 하나
- 컨테이너 (WSA, Servlet, JSP) WAS 기반으로 돌아가는 것을 의미
- WAS가 Servlet을 초기화,생성, 실행한다
- 서비스 API (JDBC, JTA, JMS, JNDI, XML…)
Servlet, JSP
- Servlet은 자바코드 기반에서 HTML이 들어가있다(WEB 페이지 만들기가 어렵다)
- 그래서 만들어진 것이 JSP. HTML안에 자바코드가 들어가있다
- 서블릿, JSP는 같다. 밀접한 관계(WAS가 JSP를 서블릿으로 변경해준다)
- Servlet은 비즈니스 로직을 처리
- JSP는 출력된 결과 처리
서블릿 클래스 작성
- HttpServlet 클래스를 상속해서 class를 만들어야 한다
- 서블릿 클래스=>서블릿객체=>서블릿
- 멀티 스레드에서는 데이터 관리를 신경써야 한다
- request : 요청
- response : 응답
JSP 작성
- 자바코드는 ‘<%’로 시작한다
- Java코드(처리)와 JSP가 섞이면 복잡하므로 처리부분은 Servlet에서 작성한다
<%@ page import ="java.text.SimpleDateFormat" %>
<%@ page import ="java.util.Calendar" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>JSP예제</h1>
<%
Calendar date = Calendar.getInstance();
SimpleDateFormat today =
new SimpleDateFormat("YYYY년 MM월 DD일");
%>
오늘은 <%=today.format(date.getTime()) %>
</body>
</html>
- E:\work\jsp_work.metadata.plugins\org.eclipse.wst.server.core\tmp0\work\Catalina\localhost\Servers\org\apache\jsp\JSP
- 위는 실제 실행되는 java파일 위치
- JSP가 java파일로 변환되었고 그 파일이 실제로 실행됨
JSP, Servlet 예제
- form.jsp에서 주는 값 2개를 FormServlet.java에서 받아서 결과계산 후 다시 result.jsp url을 요청해서 결과값을 넘겨준다
- form.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- action위치는 Project명/Servlet파일명 -->
<form action="/Servers/FormServlet" method="post">
숫자1:<input type="text" name="num1">
숫자2:<input type="text" name="num2">
<input type="submit" value="계산">
</form>
</body>
</html>
- FormServlet.java
- Post방식으로 호출했으므로 doPost 함수가 호출됨
import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/FormServlet") public class FormServlet extends HttpServlet { private static final long serialVersionUID = 1L; public FormServlet() { super(); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); int num1 = Integer.parseInt(request.getParameter("num1")); int num2 = Integer.parseInt(request.getParameter("num2")); int result = num1 + num2; request.setAttribute("result", result); // jsp가 위치한 폴더이름/jsp파일이름 RequestDispatcher re = request.getRequestDispatcher("/JSP/result.jsp"); re.forward(request, response); } } - result.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
결과:${result}
</body>
</html>
redirect, dispatcher
- Dispatcher는 A->B->C로 요청이 들어가면 B->C로 이동할 때 url이 C로 바뀌지 않고 B url 그대로 있다
- Dispatcher는 url을 기존 그대로 사용한다. 같은 요청이므로 데이터를 사용할 수 있다
- redirect는 다른 요청이므로 데이터를 사용할 수 없다. url도 다르다
- 그래서 redirect 사용 시 데이터의 값이 출력되지 않는다. 데이터를 사용하지 못하기 때문
// dispatcher
RequestDispatcher re = request.getRequestDispatcher("/JSP/result.jsp");
re.forward(request, response);
// redirect
response.sendRedirect("JSP/result.jsp");
java null object pattern
2018-12-26 00:00:00 +0000- User.java
public abstract class User {
protected String name;
public abstract boolean isNull();
public abstract String getName();
}
- Player.java
public class Player extends User{
public Player() {}
public Player(String _name) {
name = _name;
}
@Override
public boolean isNull() {
return false;
}
@Override
public String getName() {
return name;
}
}
- NullPlayer.java
public class NullPlayer extends User{
public NullPlayer() {}
public NullPlayer(String _name) {
name = _name;
}
@Override
public boolean isNull() {
return true;
}
@Override
public String getName() {
return "Null Player";
}
}
- PlayerFactory
public class PlayerFactory {
public PlayerFactory(){}
public User create(String name) {
if(name.equals("PlayerName"))
return new Player(name);
return new NullPlayer(name);
}
}
- Main.java
public class Main {
public static void main(String[] args) {
PlayerFactory playerFactory = new PlayerFactory();
User user1 = playerFactory.create("PlayerName");
User user2 = playerFactory.create("Unkown");
System.out.println("user1:"+user1.getName());
System.out.println("user2:"+user2.getName());
}
}
Posts
-
Interceptor(인터셉터)
-
Android Studio Install
-
계층형 게시판
-
VirtualBox Ubuntu 18.04.2 LTS
-
TransactionAwareDataSourceProxy Error
-
Java Coding Conventions
-
Java Long과 long의 차이
-
Mybatis 객체 안에 객체 매핑
-
JavaConfig mariadb 연결
-
DataTable
-
관리자 페이지
-
MappingJackson2JsonView
-
Spring Javaconfig
-
게시판 만들기-제품 등록
-
게시판 만들기-제품 페이지 제작
-
게시판 만들기-회원탈퇴 및 게시판 삭제 플래그 추가
-
footer 하단에 고정시키기
-
bootstrap4 사용법
-
Spring 데이터 검증 @Valid, BindingResult
-
brackets 실시간 미리보기
-
Spring 기본설정(pom.xml, web.xml, encoding)
-
Vue.js computed, methods, watch
-
javascript onkeyup
-
Maria DB Incorrect string value Error
-
javascript 암호화(md5, base64)
-
Vue.js template
-
Vue.js 소개
-
Nexacro 설명
-
ControllerAdvice
-
Batch
-
html 페이지 로딩 순서
-
소수구하기(PrimeNumber)
-
최소공배수,최대공약수
-
Stream
-
Lambda(람다식)
-
inner class(내부 클래스)
-
final 키워드
-
file upload
-
파이썬 빅 데이터 K-평균(K-means)
-
아나콘다(Anaconda), 주피터 개발환경 세팅
-
텐서플로우(TensorFlow) 아키텍쳐 및 Session
-
텐서플로우(TensorFlow)상수, 변수, 함수
-
머신러닝 기초
-
한글 리스트 오름차순, 내림차순
-
연속된 글자의 갯수 출력
-
java spring5 프로젝트 설정
-
restController
-
spring 세팅 및 기본설정
-
mybatis trim
-
jquery datepicker
-
ajax로 데이터 전달/응답 받는법
-
mybatis error
-
mybatis 게시판 만들기 순서
-
Java Jsp Mybatis Dynamic Query
-
mybatis
-
git 소개
-
node.js 개발환경 구축
-
node.js 기본 내장 모듈
-
node.js의 전역 객체
-
node.js http module
-
node.js event
-
jdbc
-
자바빈
-
jsp, servlet 정리
-
java null object pattern
-
다음지도 key 등록(kakao map)
-
공공 데이터 open api
-
facebook login api
-
sourcetree 사용법
-
JavaScript event3
-
JavaScript jquery
-
JavaScript dom
-
JavaScript ajax
-
JavaScript 이벤트2
-
JavaScript 캡슐화
-
JavaScript Array,내장객체
-
JavaScript var
-
JavaScript 객체,생성자
-
JavaScript 함수,클로저
-
JavaScript Event
-
javascript eclipse 자동완성(with tern)
-
CSS position
-
HTML5,CSS 선택자
-
자바 시간 측정
-
git,eclipse 연동
-
HTML 기초 정리
-
Eclipse Web 환경세팅
-
피보나치의 수
-
Oracle 반복문,커서,예외,저장 서브프로그램
-
Oracle PL/SQL
-
Oracle 다중쿼리(Multiple row query)
-
Oracle 인덱스, 뷰, 시퀀스, 트랜잭션, 세션 정리
-
Oracle JOIN 정리
-
Oracle DDL, DML 정리
-
Oracle 문자열 함수 정리
-
Oracle 숫자,날짜,자료형 변환 함수 정리
-
Oracle 제약조건 정리
-
Oracle 기초 쿼리 정리
-
문제2775
-
DFS
-
junit
-
json
-
algorithmus basic
-
circular queue(원형큐)
-
binary search(이진탐색)
-
port forwarding(포트포워딩)
-
kakao chatbot(카카오 챗봇)
-
java io
-
sort comparable, comparator
-
Unresolved compilation problem
-
ArrayList, HashMap
-
Regular(정규표현식)
-
Enum Class
-
String Function
-
refactoring 이란(상수,제어플래그,assert)
-
reference,abstract 정리
-
FileNotFoundException Solve
-
static
-
Thread Synchronization(스레드동기화,원자성)
-
Java Exception(예외처리)
-
Java 생성자, this, super
-
roomnum
-
BeeHouse
-
Git Reset, Revert
-
Git Log
-
Array
-
stack
-
pyramid draw
-
Star Draw(별 그리기4)
-
Star Draw(별 그리기3)
-
Star Draw(별 그리기2)
-
Star Draw(별 그리기1)
-
Loop(While, For)
-
자바 데이터 타입, 데이터 연산
-
시계방향 달팽이 그리기
-
정수값의 짝수,홀수 갯수 구하기
-
java, Scanner 정리
-
draw dog
subscribe via RSS