고급 웹 프로그래밍 기술
 - 리스너
 - 필터
=> 프로그램 전반에 영향을 줌
=> 프레임워크(Spring)에서 기본적으로 제공되는 경우가 다수

리스너
웹 환경에서 발생하는 특정 이벤트 상황을 모니터링 하다가 실행되는 특수한 형태의 서블릿
-> 특정 이벤트에 따라 실행되는 인터페이스를 구현한 클래스
@WebListener <<< 
(DB대신으로 사용....!)
-> 웹 어플리케이션에 초기 데이터를 공급
-> 특정 상황에 따라 자동으로 동작하는 프로그램을 구현
ex) 세션 장바구니에 물품을 추가하면 자동으로 계산
"초기화 매개변수"

초기화 매개변수
웹 어플리케이션 외부에서 웹 어플리케이션이 구동될때 로딩시킬 수 있는 정보
별도의 설정을 하는 이유 : 웹 어플리케이션 전반에서 공통적으로 사용하는 목적으로 설정
-> 높은 응집도를 위해서
일반적으로 프로그램을 동작시킬때 필요한 기본정보는, 소스코드내에 하드코딩하지 않고 별도의 환경설정파일을 통해 제공한다!
-> 보통 web.xml에서 설정하는 경우가 많다.
-> 서블릿 기반으로 진행할경우는 @으로 설정하는 경우가 많다.


----------------------------------------------------------------------------------------------------------------------------------------------

필터
특수한 기능을 수행하는 서블릿
ex) 정수기 필터
사용자의 요청을 처리하기 전에 req,res 객체들을 가로채서 사전에 필터에 정의된 기능을 수행한 후, 원래요청을 처리해줌!
-> ex) 국제화(다국어 처리)
-> 로깅처리


'JAVA' 카테고리의 다른 글

서블릿, JSP, DB연동  (0) 2021.09.10
JDBC와 DBCP 개념 정리  (0) 2021.09.10
JSP 포워딩 vs 리다이렉팅  (0) 2021.08.25
JSP 내장객체 exception  (0) 2021.08.25
JSP 내장객체  (0) 2021.08.25

"서블릿"
HttpServlet을 상속받아 만든 클래스
특수한 기능을 수행하는 클래스
@ 어노테이션 설정이 상단에 위치함
Java 코드 내부에 HTML코드 작성 가능

-> HTML코드를 작성하는데, 내부에 JAVA코드를 작성할수 있는 기술

-> JSP
 : 후에 Servlet.java로 변경된 코드들 

 JSP 내장객체
 : request, response, session, application, ...
 -> 설계
 1) 페이지 흐름
 2) 유지되어야하거나, 전달되어야하는 데이터 파악

<% 지시어
<jsp: 액션 실습
-> scope 개념
session : 로그인, 장바구니
applicstion : 방문자수, 판매금액, 조회수

DB연동
① 컨트롤러
M : model.테이블명 - DAO, VO
V : .HTML -> .JSP(자바코드, 알고리즘 제거하는것이 목표)
-> 커스텀태그, JSTL, EL + 템플릿

② View 역할을 하는 .jsp페이지 상단에 <% 으로 Java 알고리즘 구현
(View에서 사용자(클라이언트)가 브라우저로 요청 <- Controller 에서 어떤 정보를 넘겨줄지 선택 -> Model에서 DB를 넘겨줌

③ .jsp로 C부분을 분리
=> 원래는 C역할의 .jsp가 다수필요 하지만, 하나의 페이지에 함께 작성하여 관리
=> action 요청 파라미터를 이용!

어떻게 설계하는가?
- index.jsp로 시작
- hidden
- name 맞추기 -> 로깅 확인
- foreach에 대하여 jstl custom tag 사용
+응용
- 커스텀태그
-> 기능에 따라서 캡슐화
=> if문으로 로그인 or 로그아웃 : jstl
로그인커스텀태그 or 로그아웃 커스텀태그
 - 메인페이지에 로그인 화면을 함께 구성
 - 모든 기능을 CRUD에서 해결
insert
selectAll : 전체결과보기, 검색결과만 보기
selectOne
update
delete

'JAVA' 카테고리의 다른 글

리스너, 초기화 매개변수, 필터  (0) 2021.09.10
JDBC와 DBCP 개념 정리  (0) 2021.09.10
JSP 포워딩 vs 리다이렉팅  (0) 2021.08.25
JSP 내장객체 exception  (0) 2021.08.25
JSP 내장객체  (0) 2021.08.25

[ DB 커넥션 풀 : DBCP ]
JDBC와 DBCP의 관계를 관공서 볼펜을 예시로 들면
JDBC는 관공서에서 창구원들이 직접 볼펜을 주고 받는 경우
DBCP는 책상위에 달린 볼펜
볼펜을 직접 주고 받을 경우는 창구원의 번거로움과 이용자가 가져갈수 있다는 불편사항이 있는데 
책상위에 달린 볼펜은 사용자가 쓸일이 있는걸 알고 만든것이기 때문에 그럴 일이 없다!

DB의 연결성능 향상
- 커넥션
: 앱(프로그램)과 DB의 연결 : Connection conn = DriverManager
-> DB에 접속하고 종료하는 일련의 동작과정
다수의 연결, 정확하지 않은 연결, 종료되지 않는 연결 -> 시스템부하
 -> 최대연결커넥션 초과로 DB접속이 아예 불가능 -> 비용손실
=> 필요한 정보를 클라이언트의 DB에 일부 저장해서 서버의 부하를 낮춤
=> 데이터일치를 위한 알고리즘, 보안이 필요!

- 트랜잭션
: 여러작업을 하나의 작업처럼 단위화
작업단위 

[ DBCP ]
 일정한 개수의 커넥션을 미리 확보(ConnectionPool)하고, 클라이언트가 요청시에 이미 확보한 커넥션을 앱에 제공하는 서비스

기존 : 클라이언트 -> 웹 -> JDBC -> DB
DBCP : 클라이언트 -> 웹 -> JNDI -> 커넥션풀 -> DB

이용순서
1) 웹 에플리케이션 서버(톰캣)이 시작 -> 커넥션미리 생성
2) 생성된 커넥션 객체를 요청이 들어왔을때 JNDI를 이용해 전달
JNDI (Java Naming and Directory Interface)
: 어떤 과정이나 절차, 알고리즘 등을 캡슐화하여 처리
네이밍서비스 : 가장의 이름을 자바객체, 서비스파일, 서버 등으로 연결해줌
3) 사용하지 않는 커넥션 종료, 최소한의 커넥션을 유지

커넥션풀
 과거에는 서버 종속적이여서 서버별로 다르고, 개발자가 직접 클래스를 구현해야 했음 ==> 호환성문제와 유지보수, 성능보장에 문제가 생김! 
 현재는 서버(톰캣)에 DBCP가 내장되어 있어서 문제해결
 DBCP : JDBC에서 제공하는 DataSource 인터페이스를 활용
 JNDI를 통해 DataSource인터페이스를 제공받을 수 있음

설정방법
 1. 톰캣서버에 DataSource를 등록
server.xml or context.xml
(.xml == 설정)
(server.xml은 잘못 건들이면 프로그램 자체가 위험하기 때문에 context.xml으로 설정)
: DBCP 자원등록설정

 2. JNDI 연결할때 필요한 각종 설정 추가
웹 어플리케이션에서 참조하는 각종 서버 리소스에 대한 설정을 변경해야함
web.xml

 

<resource-ref>
<res-auth>Container</res-auth> <!--이런 자격을 가진-->
<res-type>javax.sql.DataSource</res-type> <!--이런 타입을 가진-->
<res-ref-name>jdbc/orcl</res-ref-name> <!--이 DB를 가져오겠다-->
</resource-ref>

'JAVA' 카테고리의 다른 글

리스너, 초기화 매개변수, 필터  (0) 2021.09.10
서블릿, JSP, DB연동  (0) 2021.09.10
JSP 포워딩 vs 리다이렉팅  (0) 2021.08.25
JSP 내장객체 exception  (0) 2021.08.25
JSP 내장객체  (0) 2021.08.25

메인.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%
   request.setCharacterEncoding("UTF-8");
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>포워딩 vs 리다이렉팅</title>
</head>
<body>

	<form action="forward.jsp" method="post">
		<input type="text" name="username"> <input type="submit"
			value="페이지 이동">
	</form>

	<hr>

	<form action="response_sendRedirect.jsp" method="post">
		<input type="text" name="username"> <input type="submit"
			value="페이지 이동">
	</form>
	<!-- response객체를 주체로한 리다이렉팅 방식은 jsp액션태그(포워딩)와 다르게, 페이지를 전환/이동 할때에 request,response 객체를 새로 생성함 -->


</body>
</html>

result.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>결과 페이지</title>
</head>
<body>

<h1><%=request.getParameter("username") %></h1>
<h1><%=request.getParameter("email") %></h1>

</body>
</html>

forward.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
	<%
   request.setCharacterEncoding("UTF-8");
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>포워딩 방식</title>
</head>
<body>
	<jsp:forward page="result.jsp">
	<jsp:param value="spsbsc@naver.com" name="email"/>
	</jsp:forward>
</body>
</html>

response_sendRedirect.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
	<%
   request.setCharacterEncoding("UTF-8");
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>리다이렉팅 방식</title>
</head>
<body>
	<%response.sendRedirect("result.jsp"); %>
</body>
</html>

 

forward 결과
리다이렉팅 결과

리다이렉팅은 객체를 새로 만들기 때문에 값이 비워진채로 전달됨!

'JAVA' 카테고리의 다른 글

서블릿, JSP, DB연동  (0) 2021.09.10
JDBC와 DBCP 개념 정리  (0) 2021.09.10
JSP 내장객체 exception  (0) 2021.08.25
JSP 내장객체  (0) 2021.08.25
JSP로 계산기 만들기  (0) 2021.08.24
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8" isErrorPage="true"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>에러처리 페이지</title>
<style type="text/css">
#err {
	color: red;
}
</style>
</head>
<body>
	<h2>
		발생에러:<span id="err"> <%=exception%></span>
	</h2>
</body>
</html>​
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" import="java.util.Date" errorPage="error.jsp"%><%--페이지 지시어 
    import == 자바의 여러가지를 할 수 있다
    errorPage == 현재페이지에서 오류 발생시 보내는 페이지, 해당하는 페이지에 isErrorPage = true로 에러페이지에서 exception 표기 가능--%>
    
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
String str = "test";
int i = Integer.parseInt(str);
%>
<%--<%스크립트릿 : 순수 자바코드만 사용가능 --%>
</body>
</html>

 

'JAVA' 카테고리의 다른 글

JDBC와 DBCP 개념 정리  (0) 2021.09.10
JSP 포워딩 vs 리다이렉팅  (0) 2021.08.25
JSP 내장객체  (0) 2021.08.25
JSP로 계산기 만들기  (0) 2021.08.24
JSP이용하여 커피 키오스크 만들기  (0) 2021.08.24

[ JSP 내장객체 ]
request
사용자의 입력정보가 담긴 객체(요청정보)

response
요청에 대한 응답

out
사용자에게 전달할 페이지를 작성하는 output 스트림

exception
예외처리

session
클라이언트의 세션정보가 담긴 내장객체, 유효범위가 브라우져 단위(ex. 로그인정보)

application
웹서버의 어플리케이션을 처리하는 내장객체
컨테이너(톰캣) 단위
ex) 일일 방문자수

=> Object단위로 데이터를 보관

'JAVA' 카테고리의 다른 글

JSP 포워딩 vs 리다이렉팅  (0) 2021.08.25
JSP 내장객체 exception  (0) 2021.08.25
JSP로 계산기 만들기  (0) 2021.08.24
JSP이용하여 커피 키오스크 만들기  (0) 2021.08.24
서블릿 vs jsp  (0) 2021.08.24
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>

<%
   // 변수 선언
   int result=0;

   if(request.getMethod().equals("POST")){
      String op=request.getParameter("op");
      
      int num1=Integer.parseInt(request.getParameter("num1"));
      int num2=Integer.parseInt(request.getParameter("num2"));
      // 파라미터 값은 문자열로 주고받음
      
      if(op.equals("+")){
         result=num1+num2;
      }
      else if(op.equals("-")){
         result=num1-num2;
      }
      else if(op.equals("*")){
         result=num1*num2;
      }
      else if(op.equals("/")){
         result=num1/num2;
      }
      
   }
%>

<html>
<head>
<meta charset="UTF-8">
<title>계산기 실습1</title>
</head>
<body>

	<h2>계산기</h2>
	<hr>
	<form method="post" name="form1">
		<input type="text" id="num1" name="num1"> <select name="op">
			<option selected>+</option>
			<option>-</option>
			<option>*</option>
			<option>/</option>
		</select> <input type="text" id="num2" name="num2"> <input
			type="submit" value="계산하기" name="btn1"> <input type="reset"
			value="다시입력" name="btn2">
	</form>
	<hr>
	<h3>
		계산결과:
		<%= result %></h3>

</body>
</html>

결과창

'JAVA' 카테고리의 다른 글

JSP 내장객체 exception  (0) 2021.08.25
JSP 내장객체  (0) 2021.08.25
JSP이용하여 커피 키오스크 만들기  (0) 2021.08.24
서블릿 vs jsp  (0) 2021.08.24
JAVA MySQL을 이용한 고객 관리 프로그램  (0) 2021.07.26

JSP 코드

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
	<% request.setCharacterEncoding("UTF-8"); %>
	<jsp:useBean id="cbean" class = "test.CoffeeBean"/>
	<%--클래스 생성 --%>
	<jsp:setProperty property="*" name="cbean"/>
	<%--setter 설정 --%>
<!DOCTYPE html>
<%
	if (request.getMethod().equals("POST")) {
		cbean.calcTotalPrice();
	}
%>
<html>
<head>
<meta charset="UTF-8">
<title>커피 키오스크</title>
<style type="text/css">
#wrap {
	margin: 0px;
	padding: 0px;
}

#priceTable {
	width: fit-content;
	text-align: center;
	position: inherit;
	padding: 5px;
	margin: 0px auto;
}

#tableHead {
	background-color: lightblue;
}

h1, h2{
	text-align: center;
	position: inherit;
	margin: 0px auto;
}
</style>
</head>
<body>
	<div id="wrap">
		<header>
			<h1>🐟🐋바다가 보이는 참치 카페🐳🐬</h1>
		</header>
		<div id="container">
			<form method="post">
				<table id="priceTable" border="1">
					<tr id="tableHead">
						<td>메뉴</td>
						<td>가격</td>
						<td>수량</td>
					</tr>
					<tr>
						<td>에스프레소</td>
						<td>2500</td>
						<td><input id="cntE" name="cntE" type="text" placeholder="수량을 입력해주세요!"></td>
					</tr>
					<tr>
						<td>아메리카노</td>
						<td>3000</td>
						<td><input id="cntA" name="cntA" type="text" placeholder="수량을 입력해주세요!"></td>
					</tr>
					<tr>
						<td>카페라떼</td>
						<td>4000</td>
						<td><input id="cntL" name="cntL" type="text" placeholder="수량을 입력해주세요!"></td>
					</tr>
					<tr>
						<td>카페모카</td>
						<td>5000</td>
						<td><input id="cntM" name="cntM" type="text" placeholder="수량을 입력해주세요!"></td>
					</tr>
					<tr>
					<td colspan="2"><input type = "reset" value = "다시입력"></td>
						<td><input id="calc" type="submit" value="계산하기!"></td>
					</tr>
				</table>
			</form>
			<h2>결재하실 금액은 <jsp:getProperty property="totalPrice" name="cbean"/>원 입니다!🐳🐠</h2>
		</div>
	</div>
</body>
</html>

JAVA코드

package test;

public class CoffeeBean {
	private int cntE;
	private int cntA;
	private int cntL;
	private int cntM;
	private int esPrice;
	private int amePrice;
	private int lattePrice;
	private int mocaPrice;
	private int totalPrice = 0;
	public CoffeeBean() {
		this.esPrice = 2500;
		this.amePrice = 3000;
		this.lattePrice = 4000;
		this.mocaPrice = 5000;
	}
	public void setEsPrice(int esPrice) {
		this.esPrice = esPrice;
	}
	public void setAmePrice(int amePrice) {
		this.amePrice = amePrice;
	}
	public void setLattePrice(int lattePrice) {
		this.lattePrice = lattePrice;
	}
	public int getCntE() {
		return cntE;
	}
	public void setCntE(int cntE) {
		this.cntE = cntE;
	}
	public int getCntA() {
		return cntA;
	}
	public void setCntA(int cntA) {
		this.cntA = cntA;
	}
	public int getCntL() {
		return cntL;
	}
	public void setCntL(int cntL) {
		this.cntL = cntL;
	}
	public int getCntM() {
		return cntM;
	}
	public void setCntM(int cntM) {
		this.cntM = cntM;
	}
	public int getEsPrice() {
		return esPrice;
	}
	public int getAmePrice() {
		return amePrice;
	}
	public int getLattePrice() {
		return lattePrice;
	}
	public int getMocaPrice() {
		return mocaPrice;
	}
	public void setMocaPrice(int mocaPrice) {
		this.mocaPrice = mocaPrice;
	}
	public void setTotalPrice(int totalPrice) {
		this.totalPrice = totalPrice;
	}
	public int getTotalPrice() {
		return totalPrice;
	}
	public void calcTotalPrice() {
		this.totalPrice += this.cntA*this.amePrice;
		this.totalPrice += this.cntE*this.esPrice;
		this.totalPrice += this.cntL*this.lattePrice;
		this.totalPrice += this.cntM*this.mocaPrice;
	}

}

실행화면

'JAVA' 카테고리의 다른 글

JSP 내장객체  (0) 2021.08.25
JSP로 계산기 만들기  (0) 2021.08.24
서블릿 vs jsp  (0) 2021.08.24
JAVA MySQL을 이용한 고객 관리 프로그램  (0) 2021.07.26
개발방법론 VMC 디자인패턴 정리  (0) 2021.07.21

+ Recent posts