쿠키 삭제 (1)

💻 Programming/JSP

[JSP] Cookies ( 쿠키 세팅, 읽기, 삭제하기)

Cookies 는 그냥 일반 text files 이죠. 아마 JSP를 공부하시는 분들이라면 이정도는 알고 계시겠죠? 

JSP로 HTTP cookies 를 다루는 법에 대해서 한번 알아볼텐데 그 전에 하나만 짚고 넘어갈까요?

사용자가 특정 사이트에 재접속 했다는 것을 웹사이트에서 어떻게 알까요?

3초만에 답이 안나온다면 아래를 읽어봅시다.

 

재접속하는 사용자를 판단하는 과정은 세 단계로 나뉩니다.

  • 서버쪽에서 쿠키를 브라우저로 보냅니다.  

  • Browser는 서버에서 보낸 쿠키를 로컬에 저장을 하겠죠.

  • 이제 사용자가 이 브라우저를 이용해서 특정사이트에 접속할 때 저장되어있는 쿠키의 정보가 서버쪽으로 전달되고 서버쪽에서는 이 정보를 이용해서 사용자를 판별할 수 있는 것이죠.  

쿠키는 다른 정보로도 사용될 수 있으니 쿠키를 다루는 법을 한번 알아보도록 하겠습니다. 여기서는 쿠키 세팅, 리셋, 읽기, 삭제하기에 대해서 알아보도록 하겠습니다.  


Cookie 해부하기

 쿠키는 보통 HTTP header 안에 세팅되어있습니다. ( JavaScript 는 직접 브라우저에 쿠키를 설정할 수 있다네요 ). 쿠키를 세팅하는 JSP 는 아래와 같은 헤더를 보낼거에요. 

HTTP/1.1 200 OK Date: Fri, 04 Feb 2000 21:03:38 GMT Server: Apache/1.3.9 (UNIX) PHP/4.0b3 Set-Cookie: name=xyz; expires=Friday, 04-Feb-07 22:03:38 GMT; path=/; domain=tutorialspoint.com Connection: close Content-Type: text/html

이미 request 객체시간에 한번 본적이 있던 내용이죠? 그런데 추가된게 하나 있네요. Set-Cookie header 입니다. 보아하니 이름, 만료일시, 경로, 그리고 도메인정보를 가지고 있네요.  

브라우저에서 쿠키를 저장하도록 설정이 되어있으면 브라우저는 이런 정보들을 만료일 전까지 저장하게 됩니다.만약 사용자가 쿠키에 설정된 경로로 접속을 하게되면 브라우저는 서버로 그 쿠키를 재전송합니다. 그 브라우저의 헤더는 다음과 같은 정보를 갖고 있을 겁니다. 

GET / HTTP/1.0 Connection: Keep-Alive User-Agent: Mozilla/4.6 (X11; I; Linux 2.2.6-15apmac ppc) Host: zink.demon.co.uk:1126 Accept: image/gif, */* Accept-Encoding: gzip Accept-Language: en Accept-Charset: iso-8859-1,*,utf-8 Cookie: name=xyz

이제 JSP script 는 request method중 하나인 request.getCookies() 를 통해서 쿠키에 접근할 수 있습니다. 

 

Servlet Cookies 메소드

아래 메소드들은 JSP에서 쿠키를 다룰때 사용될 수 있는 메소드목록 및 기능입니다.

 

S.N.Method & Description
1public void setDomain(String pattern)
This method sets the domain to which cookie applies, for example tutorialspoint.com.
2public String getDomain()
This method gets the domain to which cookie applies, for example tutorialspoint.com.
3public void setMaxAge(int expiry)
This method sets how much time (in seconds) should elapse before the cookie expires. If you don't set this, the cookie will last only for the current session.
4public int getMaxAge()
This method returns the maximum age of the cookie, specified in seconds, By default, -1 indicating the cookie will persist until browser shutdown.
5public String getName()
This method returns the name of the cookie. The name cannot be changed after creation.
6public void setValue(String newValue)
This method sets the value associated with the cookie.
7public String getValue()
This method gets the value associated with the cookie.
8public void setPath(String uri)
This method sets the path to which this cookie applies. If you don't specify a path, the cookie is returned for all URLs in the same directory as the current page as well as all subdirectories.
9public String getPath()
This method gets the path to which this cookie applies.
10public void setSecure(boolean flag)
This method sets the boolean value indicating whether the cookie should only be sent over encrypted (i.e. SSL) connections.
11public void setComment(String purpose)
This method specifies a comment that describes a cookie's purpose. The comment is useful if the browser presents the cookie to the user.
12public String getComment()
This method returns the comment describing the purpose of this cookie, or null if the cookie has no comment.


 JSP로 쿠키 설정하기

JSP로 쿠키를 설정하려면 아래와 같은 단계를 거칩니다.

 

(1) Cookie 객체 생성 : You call the Cookie constructor with a cookie name and a cookie value, both of which are strings.

Cookie cookie = new Cookie("key","value");

자바에서 쿠키 생성하는거랑 똑같습니다. 그런데 여기서 name과 value ( "key"가 name인거고 "value"가 value가 되겠죠)에는 절대로 스페이스(빈칸)이나 아래에 나열된 특수문자가 사용될 수 없습니다.  

[ ] ( ) = , " / ? @ : ;

(2) Max age 설정 : 초 단위로 max age를 설정합니다. 이 쿠키가 살아있을 수 있는 시간을 설정하는거죠. 아래는 24 시간동안 존재할 수 있는 쿠키를 설정하는 예제입니다.

cookie.setMaxAge(60*60*24);

(3) Cookie를 HTTP response header에 추가하기 : response.addCookie 메소드를 이용하면 추가하 수 있습니다.  

response.addCookie(cookie);

예제

<% // Create cookies for first and last names. Cookie firstName = new Cookie("first_name", request.getParameter("first_name")); Cookie lastName = new Cookie("last_name", request.getParameter("last_name")); // Set expiry date after 24 Hrs for both the cookies. firstName.setMaxAge(60*60*24); lastName.setMaxAge(60*60*24); // Add both the cookies in the response header. response.addCookie( firstName ); response.addCookie( lastName ); %> <html> <head> <title>Setting Cookies</title> </head> <body> <center> <h1>Setting Cookies</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 파일에 위 코드를 넣어주세요. 그리고 다음 코드는 hello.jsp파일에 넣어주세요. 

<html> <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>

두 jsp파일을 <Tomcat-installation-directory>/webapps/ROOT 디렉토리에 넣어주세요.

이제 http://localhost:8080/hello.jsp 에 접속을 해보세요.

 

 

 

이런게 나오나요? 이제 이름을 넣고 submit버튼을 눌러보세요. 

그럼 예전에 봤던 것처럼 퍼스트 네임과 래스트 네임이 출력이 될겁니다. 그런데 여기서 이녀석이 몰래하는 작업이 또 있습니다. 눈에는 보이지 않았지만 first_name과 last_name이라는 쿠키를 생성한것입니다. 그리고 submit버튼이 또 눌리게 될 경우 방금 만들어진 쿠키들이 서버쪽으로 전송되게 되겠죠. 

자, 그럼 이제 서버쪽으로 전송되는 쿠키정보를 JSP에서 읽어오는 것을 한번 해보겠습니다. 


JSP를 이용하여 쿠키정보 읽어오기

쿠키를 읽으려면 HttpServletRequest 의 getCookies( ) 메소드를 호출하기만 하면 됩니다. 이 메소드는 Cookie[]를 반환합니다. 한번에 여러개의 쿠키가 전송될 수 있다는 것이죠. 그럼 루프를 돌면서 전송된 쿠키의 정보를 출력하는 예제를 한번 보도록 하겠습니다.  


예제

<html> <head> <title>Reading Cookies</title> </head> <body> <center> <h1>Reading Cookies</h1> </center> <% Cookie cookie = null; Cookie[] cookies = null; // Get an array of Cookies associated with this domain cookies = request.getCookies(); if( cookies != null ){ out.println("<h2> Found Cookies Name and Value</h2>"); for (int i = 0; i < cookies.length; i++){ cookie = cookies[i]; out.print("Name : " + cookie.getName( ) + ", "); out.print("Value: " + cookie.getValue( )+" <br/>"); } }else{ out.println("<h2>No cookies founds</h2>"); } %> </body> </html>

위 코드를 main.jsp 파일에 넣고 접속해보세요. 쿠키에 설정한 값들이 나오겠죠? 아래처럼 말이죠.


Found Cookies Name and Value

Name : first_name, Value: 홍길동은
Name : last_name, Value: 플레이보이


JSP를 이용한 쿠키 삭제

이번에는 쿠키를 삭제해보도록 하겠습니다. 뭐 쿠키삭제는 브라우저에서도 할 수 있는 기능이긴 하지만 그래도 한번 읽어나 보세요. 웹개발자라면 쿠키 다루는 법은 잘 알고 있어야 할 테니까요. 

  • 쿠키를 읽어와서 쿠키객체에 저장합니다.

  • 쿠키의 나이를 0으로 만들어버리세요. setMaxAge() 메소드를 사용하면 되는건 아시죠?

  • 이 쿠키를 다시 response에 넣어 되돌려보내세요.


예제

아래 예제는 "first_name" 쿠키를 삭제하는 main.jsp 소스입니다. 삭제된 후에 이 쿠키를 다시 읽어오려고하면 null이 나올겁니다.

<html> <head> <title>Reading Cookies</title> </head> <body> <center> <h1>Reading Cookies</h1> </center> <% Cookie cookie = null; Cookie[] cookies = null; // Get an array of Cookies associated with this domain cookies = request.getCookies(); if( cookies != null ){ out.println("<h2> Found Cookies Name and Value</h2>"); for (int i = 0; i < cookies.length; i++){ cookie = cookies[i]; if((cookie.getName( )).compareTo("first_name") == 0 ){ cookie.setMaxAge(0); response.addCookie(cookie); out.print("Deleted cookie: " + cookie.getName( ) + "<br/>"); } out.print("Name : " + cookie.getName( ) + ", "); out.print("Value: " + cookie.getValue( )+" <br/>"); } }else{ out.println( "<h2>No cookies founds</h2>"); } %> </body> </html>

이제 main.jsp를 요청해보세요. http://localhost:8080/main.jsp 주소로 요청하면 되겠죠? 그럼 아래처럼 결과가 나올 거에요.


Cookies Name and Value

Deleted cookie : first_name
Name : first_name, Value: John
Name : last_name, Value: Player

 

 http://localhost:8080/main.jsp 를 다시한번 요청하면 아래와 같은 결과를 보게 될 거에요.

 

Found Cookies Name and Value

Name : last_name, Value: Player

 

first_name 쿠키는 삭제되어서 안나오네요.

 

어때요? 쉽죠잉?  

 




 

 

Reference : http://www.tutorialspoint.com/jsp/jsp_cookies_handling.htm