JSP/Cookies

Cookies with JSP

Soul-Learner 2008. 1. 19. 21:47
Cookie는 HTTP 프로토콜에 의해 지원되는 기능이며 웹서버가 클라이언트(웹브라우저)를 식별하기 위한 수단으로 사용된다. 즉, 쿠키는 웹서버가 웹브라우저에 응답할 때 전달하여 클라이언트의 하드디스크에 파일 형태로 저장되는 소량의 텍스트 데이터라고 할 수 있다. 쿠키를 전달받은 웹브라우저는 다시 그 웹서버에 요청할 때 쿠키를 서버에 전달하도록 되어 있다. 이런 방법으로 웹서버는 쿠키를 클라이언트에게 보냈다가 다시 받을 수가 있기 때문에 웹서버 입장에서는 접속자를 계속 추적하거나 식별할 목적으로 주로 사용된다. 이런 행위를 Session Tracking 이라고 한다. 웹브라우저에 쿠키를 전달하고 회수하는 방법에 대해 알아본다.

JSP 에서 사용되는 HTTP 쿠키는 javax.servlet.http.Cookie 클래스이며 이 클래스를 이용하여 웹서버에서는 response.addCookie(javax.servlet.htt.Cookie)메소드를 통해 HTTP 응답헤더에 담아 쿠키를 웹브라우저에 내려 보낼 수가 있고 브라우저에서 올라오는 쿠키는 HTTP 요청헤더에 포함되어 웹서버에 전달되므로 웹서버에서는 request.getCookies()메소드를 통해 회수할 수가 있게 된다. 한개의 웹서버는 한개의 클라이언트에게 총 20개의 쿠키를 내려 보낼 수 있고, 브라우저는 총 300개의 쿠키를 저장할 수 있으며, 각 쿠키의 크기는 4KB로 제한된다. 쿠키는 동일한 이름을 가질 수 있지만 동일한 이름과 동일한 PATH 속성을 동시에 가질 수는 없다.

Cookie 클래스의 생성자는 다음과 같다.
public Cookie(String name, String value)
쿠키의 이름은 아스키 문자이어야 하고 콤마, 세미콜른, 공백문자등을 포함할 수 없고 $기호로 시작해서는
안된다. 일단 쿠키가 생성된 후에는 그 이름을 변경할 수 없고, 그 값은 setValue() 에 의해 변경할 수
있다. 쿠키의 값은 아스키 문자만 사용할 수 있고 공백 문자도 사용할 수 있다.

쿠키 클래스는 다음과 같은 메소드를 갖는다.



Method

Description

getComment()

Returns the comment describing the purpose of this cookie, or null if no such comment has been defined.

getDomain()

Returns the domain name set for this cookie.

getMaxAge()

Returns the maximum specified age of the cookie.

getName()

Returns the name of the cookie.

getPath()

Returns the prefix of all URLs for which this cookie is targeted.

getValue()

Returns the value of the cookie.

setCommen(String)

If a web browser presents this cookie to a user, the cookie's purpose will be described using this comment.

setDomain(String)

Specifies the domain within which this cookie should be presented. The form of the domain name is specified by RFC 2109. A domain name begins with a dot (.foo.com) and means that the cookie is visible to servers in a specified Domain Name System (DNS) zone (for example, www.foo.com, but not a.b.foo.com). By default, cookies are only returned to the server that sent them.

setMaxAge(int)

Sets the maximum age of the cookie. The cookie will expire after that many seconds have passed. Negative values indicate the default behavior: the cookie is not stored persistently, and will be deleted when the user web browser exits. A zero value causes the cookie to be deleted

setPath(String)

This cookie should be presented only with requests beginning with this URL.

setValue(String)

Sets the value of the cookie. Values with various special characters (white space, brackets and parentheses, the equals sign, comma, double quote, slashes, question marks, the "at" sign, colon, and semicolon) should be avoided. Empty values may not behave the same way on all browsers.



 Cookie 는 웹서버가 브라우저의 요청에 응답할 때 응답헤더에 포함되어 전달될 수 있기 때문에 서버가
쿠키를 브라우저에 전달하려면 일단 브라우저에서 요청을 먼저 해야 한다. 다음에 소개할 예제는,
브라우저가 요청할 때 사용자의 ID를 폼을 통해 전달하도록 하고 서버에서는 그 이용자의 ID를 쿠키에
저장하여 다시 브라우저에 전달해 두면 다음에 브라우저가 해당 웹서버에 다시 요청할 때 그 쿠키를 다시
웹서버에 전달하고 웹서버는 쿠키에 기록된 이용자의 ID를 확인하여 Session Tracking 에 활용할 수가
있다.

cookieForm.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!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=EUC-KR">
<title>Insert title here</title>
</head>
<body><p><center>
<div style="font-size:80%">
아래의 입력란에 입력된 문자열이 서버로 전달되면 <p>
JSP 프로그램에서 그 문자열을 받아서 쿠키에 저장하여<p>
다시 브라우저에 전송하려고 합니다.<p>
<form action="cookieSet.jsp" method="post">
ID: <input type="text" name="id" value="micropilot"><br>
<input type="submit" value="SUBMIT">
</form>
</div>
</center>
</body>
</html>


cookieSet.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!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=EUC-KR">
<title>Cookie Set</title>
</head>
<body><center>

<%
 request.setCharacterEncoding("KSC5601");
 String id = request.getParameter("id");
 Cookie cookie = new Cookie("id",id);
 response.addCookie(cookie);

%>
<div style="font-size:80%">
이 페이지가 다운로드될 때 웹서버에서 설정한 Cookie가 브라우저에 저장되었습니다.<p>
아래의 링크를 클릭하시면 <br>
브라우저에 설정된 쿠키가 요청과 함께 웹서버로 다시 전달되며<br>
서버에서는 JSP 프로그램내의 request.getCookies()메소드를 이용하여 확인할 수 있습니다.<p>
그러므로 아래의 링크를 클릭하면 <br>
요청과 함께 서버로 전달되는 쿠키를 서버에서 확인하여 다시 웹브라우저의 화면에 출력해 보겠습니다.
<p>

<a href="cookieGet.jsp">현재 브라우저에 저장된 Cookie 확인하기</a>
</div>
</center></body>
</html>


cookieGet.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!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=EUC-KR">
<title>Insert title here</title>
</head>
<body><p><center>
<table>
<%
 Cookie[] cookies = request.getCookies();
 for(int i=0;i<cookies.length;i++){%>
 <tr><td align="right">Cookie name</td><td>&nbsp;&nbsp;</td><td align="left"><%=cookies[i].getName()%></td></tr>
 <tr><td align="right">Cookie value</td><td></td><td align="left"><%=cookies[i].getValue()%></td></tr>
 <tr><td colspan=3><hr></td></tr>
<% }
%>

</table>
<p>
서버에 생성된 HttpSession 객체의 고유번호(JSESSIONID)<p>
Session ID:<%=request.getSession().getId()%>
</center>
</body>
</html>


Cookie 응용 문제

위의 예제를 참조하여 다음과 같은 내용을 프로그래밍 해 보세요
이용자가 ID, Password를 입력하여 로그인하면 접속한 웹사이트에서는 그 이용자의 ID를 쿠키에 저장하여 클라이언트로 전달해 주고 그 이용자가 해당 웹사이트 내의 두번째 페이지에 접속할 때 그 이용자가 로그인 과정을 거치고 웹사이트에 들어온 이용자인지를 식별하여 정상적인 과정을 거쳤으면 해당 페이지를 서비스해 주고 아니ㅣ면 로그인 페이지로 다시 돌려 보내는 프로그램을 JSP 로 작성해 보세요