본문 바로가기

JSP

쿠키

쿠키 기술을 사용하는 목적은 웹 컴포넌트 간의 데이터 전달을 위해서지만, 이런 목적을 이루기 위해 웹 브라우저 쪽에 데이터를 저장했다가 다시 읽어오는 방식을 취하기 때문에 구체적인 기능은 데이터 관리 시스템의 형태를 띠고 있다.


쿠키데이터를 저장하는 jsp

 

<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

 

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Insert title here</title>

</head>

<body>

<!-- cookie_before.jsp  -->

<form action="cookie_ok.jsp" method="post">

아이디 : <input type="text" name="id"/><br />

이메일 : <input type="text" name="email"/><br />

<input type="submit" value="전송"/>

<br /><br />

<a href="cookie_delete.jsp">쿠키삭제</a>

 

</form>

 

</body>

</html> 

 

<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

 

<%

    request.setCharacterEncoding("utf-8");

 

    String id = request.getParameter("id");

    String email = request.getParameter("email");

   

    Cookie cookie1 = new Cookie("id", id);

    Cookie cookie2 = new Cookie("email", email);

   

    cookie1.setMaxAge(3600);

    cookie2.setMaxAge(3600);

 

    response.addCookie(cookie1);

    response.addCookie(cookie2);

%>

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Insert title here</title>

</head>

<body>

쿠키가 저장되었습니다.<br />

<a href="cookie_after.jsp">쿠키확인</a>

 

</body>

</html>

 


쿠키데이터를 읽는 jsp

 

<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

<%!

    private String getCookieValue(Cookie[] cookies, String name){

         if(cookies == null) return null;

         for(Cookie cookie : cookies){

             if(cookie.getName().equals(name)){

                  return cookie.getValue();

             }

         }

         return null;

    }  

%>

<%

    Cookie[] cookies = request.getCookies();

    String id = getCookieValue(cookies, "id");

    String email = getCookieValue(cookies, "email");

%>

 

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Insert title here</title>

</head>

<body>

쿠키 내용 : <%=id %><br />

쿠키 내용 : <%=email %><br />

 

</body>

</html>

 

쿠키데이터를 삭제하는 jsp

 

<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

<%

    Cookie cookie1 = new Cookie("id", "");

    Cookie cookie2 = new Cookie("email", "");

   

    cookie1.setMaxAge(0);

    cookie2.setMaxAge(0);

   

    response.addCookie(cookie1);

    response.addCookie(cookie2);

%>

 

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Insert title here</title>

</head>

<body>

쿠키가 삭제되었습니다.<br />

<a href="cookie_after.jsp">쿠키확인</a>

</body>

</html>


 

 

'JSP' 카테고리의 다른 글

익스프레션 언어 requestScope  (0) 2013.03.21
서블릿의 라이프 사이클  (0) 2013.03.21
익셉션 처리 실습  (1) 2013.03.20
URL 재작성 메커니즘  (0) 2013.03.20
세션  (0) 2013.03.20