Upload
others
View
1
Download
0
Embed Size (px)
Citation preview
데이타베이스시스템연구실Database Systems Lab.
충남대학교컴퓨터공학과
데이타베이스시스템연구실
12. JSP II
When a browser requests for a web page:
It sends lot of information to the web server which can not be read
directly because this information travel as a part of header of HTTP
request.
Important header information which comes from browser side. Try it!
The HttpServeltRequest Object
The request object is an instance of a javax.servlet.http.HttpSevletRequest
object.
The request object provides methods to get HTTP header information
including from data, cookies, HTTP methods, etc.
These method are available with HttpServletRequest object. Try it!
Client Request
2
HTTP Header Request Example: Try it!
Client Request (cont’d)
3
Web Browser(Layout or Rendering) Engines
4
https://en.wikipedia.org/wiki/Web_browser_engine
When a Web server responds to a HTTP request to the browser.
A summary of the most useful HTTP 1.1 response headers which go back to the browser from web server side. Try it!
Server Response
5
The HttpServeltResponse Object
The response object is an instance of a
javax.servlet.http.HttpSevletResponse object.
The request object defines the interface that deal with creating new
HTTP headers. Through this object the JSP programmer can add new
cookies or date stamps, HTTP status codes, etc.
These method are available with HttpServletResponse object. Try it!
Server Response (cont’d)
6
HTTP Header Response Example Try it!
Server Response (cont’d)
7
A list of HTTP status codes and associated messages
Methods to Set HTTP Status Code
Can be used to set HTTP Status Code in your servlet program.
Available with HTTPServletResponse object.
HTTP Status Codes
8
HTTP Status Code Example: Try it!
HTTP Status Codes (cont’d)
9
브라우저는사용자의입력정보를웹서버에게보내기위해두가지방법을사용
GET 방식, POST 방식
GET 방식페이지요청에첨가하여인코딩된 정보를보내는방법.
브라우저의 Location box에나타나며, 인코딩된정보는 ? 문자에의해분리
request 객체의 getQueryString( )과 getParameter( ) 메소드를이용하여처리할수있음
getQueryString () : 요청URL에포함된질의스트링을넘김
getParameter ( ) : 요청변수의값을넘김
폼처리
10
http://www.test.com/hello?key1=value1&key2=value2
POST 방식일반적으로 더신뢰할수있는방법
메시지 Body의일부로웹서버에전송
getParameter () 와 getInputStream( )을이용하여처리
getParameter ( ) : 단순한변수들을읽기위해사용
getInputStream( ) : 클라이언트로부터온바이너리데이터스트림을읽기위해사용
그외폼데이터처리메소드getParameterValues ( )
Checkbox와같이하나의변수에대해여러개의값이넘겨질경우 사용
getParameterNames ( )
현재의 request에있는모든변수들의리스트를원할경우사용
폼처리 (cont’d)
11
Ex. 1: GET Method 예 : get-ex1.html
12
<html><head>
<title> Get Method example</title></head><body>
<form action="main.jsp" method="GET">First Name: <input type="text" name="first_name"> <br>Last Name: <input type="text" name="last_name">
<input type="submit" value="submit"></form>
</body></html>
GET Method 예 : main.jsp (cont’d)
13
<html><head>
<title> Using GET Method to Read Form Data</title></head><body>
<center><h1> Using GET Method to Read Form Data</h1></center><ul><li><p><b>First Name:</b>
<%=request.getParameter("first_name")%></p></li><li><p><b>Last Name:</b>
<%=request.getParameter("last_name")%></p></li></ul>
</body></html>
main.jsp코드는 “Using POST Method to Read Form Data” 부분만다르고 페이지 13과동일
Ex. 2: POST Method 예 : post-ex2.html
14
<html><head>
<title> Get Method example</title></head><body>
<form action="main.jsp" method=“POST">First Name: <input type="text" name="first_name"> <br>Last Name: <input type="text" name="last_name">
<input type="submit" value="submit"></form>
</body></html>
checkboxMain2.jsp for Ex. 3
Ex. 3(cont’d)
16
JSP 페이지의내장변수 (implicit variable)
17
내장변수란 ? JSP 페이지에서선언하지않고도사용할수있는변수
request 내장변수 : 서블릿클래스에있는 doGet, doPost메소드의첫번째파라미터와동일
out 내장변수 : 서블릿클래스안에있는 getWriter메소드를호출해서얻은PrintWriter객체와마찬가지역할(강의자료 JSP I의 page 6의예에서)
<%page contentType=“text/html; charset=UTF-8”%><HTML>
<HEAD><TITLE>정수를순서대로</TITLE></HEAD><BODY>
<H3> 정수를순서대로</H3><%
String str = request.getParameter(“MAX”);int max = Integer.parseInt(str);
for (int cnt=1 ; cnt <= max; cnt++)out.printIn(cnt + “<BR>”);
%></BODY>
</HTML>
내장변수
JSP 페이지에서이런내장변수를사용할수있는이유웹컨테이너가 JSP 페이지를서블릿클래스로변환할때자동으로선언해주기때문
JSP 페이지의내장변수 (cont’d)
18
변수 이름 제공하는 기능/변수의 역활 변수 타입
request
• 클라이언트로부터 정보를 추출
• doGet, doPost 메소드의 첫번째파라미터와 동일한 역할
javax.servlet.http.HttpServletRequest
response
• 클라이언트에 정보를 전송
• doGet, doPost 메소드의 두번째파라미터와 동일한 역할
javax.servlet.http.HttpServletResponse
out• 웹 브라우저로 HTML 코드를출력하는 기능
javax.servlet.jsp.JspWriter
session• 클라이언트와 서버 간의 연결을유지
javax.servlet.http.HttpSession
본강의에서는위의내장변수들중에서 request, response, out, application, session에대한것만다룰것임
JSP 페이지의내장변수 (cont’d)
19
변수 이름 제공하는 기능/변수의 역할 변수 타입
page• JSP 페이지에 의해 생성되는서블릿을 나타내는 객체
java.lang.Object
config• JSP 페이지에 대한 초기 설정정보를처리
javax.servlet.ServletConfig
application • 웹 애플리케이션의 정보처리를 도움 javax.servlet.ServletContext
pageContext• JSP 페이지 범위 내에서 정보 공유를도움
javax.servlet.jsp.PageContext
exception • 예외 상황 발생 시 처리 java.lang.Exception
request 내장변수
20
서블릿클래스에있는 doGet, doPost메소드의첫번째파라미터와동일한역할
Javax.servlet.http.HttpServletRequest와동일한타입
내장변수에대해 getParameter메소드를호출하면웹브라우저를통해입력된데이터를가져올수있음
예제‘YourName.html’을통해이름을입력받고, 그이름을포함한인사말을만들어서오른쪽화면페이지에출력하는예제
String str = request.getParameter(“YOURNAME”);
데이터이름
예제소스
21
<HTML><HEAD>
<META http-equiv="Content-Type" content="text/html;charset=UTF-8"><TITLE>이름입력</TITLE>
</HEAD><BODY>당신의이름을입력하세요.<FORM ACTION=/brain12/Hi.jsp METHOD=GET>이름: <INPUT TYPE=TEXT NAME=YOURNAME><INPUT TYPE=SUBMIT VALUE='확인'>
</FORM></BODY>
</HTML>
<%@page contentType="text/html; charset=UTF-8"%><HTML>
<HEAD><TITLE>인사하기</TITLE></HEAD><BODY>
안녕하세요, <%= request.getParameter("YOURNAME") %>님</BODY>
</HTML>
YourName.html
Hi.jsp
out 내장변수
JSP 페이지가생성한결과를웹브라우저에전송해주는출력스트림
이내장변수는출력하는데이터를일단버퍼에저장했다가한꺼번에전송
out.print, out.println메소드를호출할경우뿐만아니라, HTML 코드나익스프레션을통해출력할경우에도 out 내장변수를통해출력
예제
out 내장변수 (cont’d)
23
<%@page contentType="text/html; charset=UTF-8"%><HTML>
<HEAD><TITLE>1부터 10까지순서대로</TITLE></HEAD>
<BODY><H3>1부터 10까지순서대로</H3><% for (int cnt=1; cnt <= 10; cnt++) { %>
<%= cnt %> <BR><% } %>
</BODY></HTML>
<%@page contentType="text/html; charset=UTF-8"%><HTML>
<HEAD><TITLE>1부터 10까지순서대로</TITLE></HEAD><BODY>
<H3>1부터 10까지순서대로</H3><%
for (int cnt=1; cnt <= 10; cnt++) out.println(cnt + "<BR>");
%></BODY>
</HTML>
=
버퍼의크기는웹컨테이너의종류에따라달라질수있으나, 기본적으로 8KB 이상의버퍼를만들어야함
page 지시자의 buffer 애트리뷰트를이용해서버퍼의크기를바꿀수있음
버퍼의실제크기를알기위해
출력버퍼의크기를바이트단위로넘김
out 내장변수를통해출력되는내용이버퍼를거치지않고웹브라우저로바로바로전송되기위해
out 내장변수 (cont’d)
24
<%@page buffer=“10kb” %>
int bsize = out.getBufferSize( );
<%@page buffer=“none” %>
버퍼의내용이웹브라우저로자동으로전송되지않도록하기위해
버퍼의모든내용을웹브라우저로보내고버퍼를비우는메소드
out 내장변수 (cont’d)
25
<%@page autoFlush=“false” %>
out.flush( );
response 내장변수
26
서버에서클라이언트로의응답할응답정보를가지고있는객체
javax.servlet.http.HttpServletResponse인터페이스에서제공하는여러가지메소드호출가능
response의 contents type과 encoding 설정
setContextType(String type) Response contents의 MIME 타입과 문자 encoding설정
getCharacterEncoding() Response contents의 문자 encoding style set 반환
response 내장변수 (cont’d)
27
response header setting
addCookie(cookie) 지정된 쿠키를 응답에 추가
containsHeader(name) name 이름의 헤더가 응답에 포함되어 있는지 검사
setHeader(name,value) name 이름의 헤더에 문자열 값 삽입
setIntHeader(name,value) name 이름의 헤더에 정수 값 삽입
setDateHeader(name,date) name 이름의 헤더에 날짜 값 삽입
addHeader(name,value) name 이름의 헤더와 value 이름의 문자열 값 붙여서 추가
addIntHeader(name,value) name 이름의 헤더와 value 이름의 정수 값 붙여서 추가
addDateHeader(name,date) name 이름의 헤더와 value 이름의 날짜 값 붙여서 추가
response 내장변수 (cont’d)
28
응답코드 setting
sendRedirect ( )의예
setStatus(code) 응답의 상태 코드설정
sendError(status,msg) 응답의 상태 코드와 에러 메시지 설정
sendRedirect(url) 지정된 URL로 jump
<% response.sendRedirect("http://dblab.cnu.ac.kr/"); %>
특정웹애플리케이션디렉토리에속하는모든웹자원들의집합에관련된여러가지기능을제공
getContextPath( )
웹애플리케이션의URL 경로명을리턴하는메소드
예: brain 웹애플리케이션안에서실행하면 ‘/brain’을리턴
예: ROOT 웹애플리케이션안에서실행하면, 길이가 0인문자열을리턴
getRealPath( )
웹애플리케이션내에서의파일경로명을파일시스템전체에서의절대경로명으로바꾸는메소드
application 내장변수
29
application 내장변수예제
30
<%@page contentType="text/html; charset=UTF-8"%><HTML>
<HEAD><TITLE> applicaton내장변수의사용예</TITLE>
</HEAD><BODY>
<%String appPath=application.getContextPath();String filePath = application.getRealPath("/sub1/test.html");
%>웹애플리케이션의URL 경로명 : <%=appPath %><BR>/sub1/test.html의파일경로명 : <%=filePath %><BR>
</BODY></HTML>
세션(session)?JSP makes use of servlet provided HttpSession Interface which provides a way to identify a user across more than one page request or visit to a Web site and to store information about that user
여러웹컴포넌트들이협력작업을시작해서끝내기까지의기간
세션을시작하고끝내는기능
그기간동안웹컴포넌트들이데이터를주고받을수있는기능
Session 내장변수를사용하여세션데이터영역에데이터를저장할수도있고, 그영역에있는데이터를읽어오거나삭제할수도있음
세션 (sesson)
31
세션데이터를저장하는메소드
세션데이터를가져오는메소드
세션데이터를삭제하는메소드
세션을끝내는메소드
세션 내장변수에서지원하는메소드들
32
session.setAttribute(“ID”, “lee77”);
String str = (String) session.getAttribute(“ID”);
session.removeAttribute(“ID”);
session.invalidate( );
회원가입예제 Try it!
33
선택 : 동의함
선택 : 동의하지않음
Join.html Agreement.jsp
Result.jsp
Subscribe.jsp
회원가입을위한화면아이디
패스워드
이름
예제설명 : Join.html
34
<HTML>
<HEAD><META charset="UTF-8"/><TITLE>JSP 전체예제 : 회원가입</TITLE>
</HEAD>
<BODY>개인정보를입력하세요.<BR><BR>
<FORM ACTION=Agreement.jsp METHOD=POST>아이디: <INPUT TYPE=TEXT NAME=ID><BR>패스워드:<INPUT TYPE=PASSWORD NAME=PASSWORD><BR>이름: <INPUT TYPE=TEXT NAME=NAME><BR><BR><INPUT TYPE=SUBMIT VALUE='확인'>
</FORM>
</BODY></HTML>
예제설명 : Aggrement.jsp
35
<%@page contentType="text/html; charset=UTF-8"%><%
request.setCharacterEncoding("UTF-8");String id = request.getParameter("ID");String password = request.getParameter("PASSWORD");String name = request.getParameter("NAME"); session.setAttribute("ID", id);session.setAttribute("PASSWORD", password);session.setAttribute("NAME", name);
%><HTML>
<HEAD<TITLE>회원가입</TITLE></HEAD><BODY>
<H3>약관</H3>-------------------------------------------------------------------------<BR>1. 회원정보는웹사이트의운영을위해서만사용됩니다.<BR>2. 웹사이트의정상운영을방해하는회원은탈퇴처리합니다.<BR>-------------------------------------------------------------------------<BR><FORM ACTION=Subscribe.jsp METHOD=POST> 위의약관에동의하십니까?<INPUT TYPE=RADIO NAME=AGREE VALUE=YES> 동의함<INPUT TYPE=RADIO NAME=AGREE VALUE=NO> 동의하지않음.<BR><BR><INPUT TYPE=SUBMIT VALUE='확인'></FORM> </BODY>
</HTML>
예제설명 : Subscribe.jsp
36
<%@page contentType="text/html; charset=UTF-8"%><%@page import="java.io.*"%><% String agree = request.getParameter("AGREE");
String result = null; if (agree.equals("YES")) {
String id=(String) session.getAttribute("ID");String password=(String) session.getAttribute("PASSWORD");String name=(String) session.getAttribute("NAME");PrintWriter writer=null;
try {String filePath = application.getRealPath("/JSP-ex/sub1/"+id+"txt");writer=new PrintWriter(filePath);writer.println("아이디:" + id);writer.println("패스워드:" + password);writer.println("이름:" + name);result="SUCCESS"; }
catch (IOException ioe) { result="FAIL"; }finally {
try { writer.close();}catch (Exception e) { …}}}
else { result="FAIL"; }session.invalidate();response.sendRedirect("Result.jsp?RESULT="+result);
%>
예제설명 : Result.jsp
37
<%@page contentType="text/html; charset=UTF-8"%><% String result=request.getParameter("RESULT");%><HTML>
<HEAD><TITLE>회원가입</TITLE></HEAD><BODY>
<H3>회원가입결과</H3><%
if(result.equals("SUCCESS"))out.println("가입되었습니다.");
elseout.println("가입되지않았습니다.");
%></BODY>
</HTML>
Consider a webpage
Is displaying live game score or stock market status or currency
exchange ration. For all such type of pages, you would need to refresh
your web page regularly using refresh or reload button with your
browser.
You can make a webpage in such a way that it would refresh
automatically after a given interval.
Using method setIntHeader( ) of response object.
Auto Refresh
38
JSP 기술과서블릿기술을혼용
40
실무에서작성할웹애플리케이션중에는휠씬더복잡한로직을필요로함
HTML 중심의코드구조가오히려소스코드를이해하기어렵게만들수있음
소스코드를그대로저장하는방식은보안이쉽지않음
로직의유출및타인에의한코드변경등
요즘은 JSP 기술과서블릿기술을혼용한새로운프로그래밍방법이권장됨프로그래밍의기능을구현하는복잡한로직은서블릿클래스안에기술
그결과를가져다가출력하는일만 JSP 페이지가담당
서블릿과 JSP 기술을혼합해서작성한웹애플리케이션
41
<HTML><HEAD><TITLE>1부터 100까지의합</TITLE></HEAD><BODY>1부터 100까지의합은? ${result}</BODY></HTML>
public class HundredServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {int total = 0;for (int cnt = 1; cnt<=100; cnt++)
total += cnt;request.setAttribute(“result”, total);RequestDispatcher rd=request.getRequestDispatcher(“Hundred.jsp”);rd.forward(request, response);
}}
1. 1부터 100까지의수를더해서그결과를 result 라는이름으로저장
2. JSP 페이지를호출
3. result 값을출력