본문 바로가기
Spring/JSP

[JSP] 쿠키(Cookie)

by JJH0100 2022. 11. 21.
728x90
반응형

쿠키 생성 단계

1. 쿠기 객체 생성 및 속성값 설정

Cookie c = new Cookie("id", "test");

 

2. 유효기간 설정

c.setMaxAge(60*3); //3분

 

3. 클라이언트에 쿠키 전송

response.addCookie(c);

 

++ 다음과 같이 한 줄로 설정 할 수도 있다.

response.addCookie(new Cookie("id", "test"));

 

 


 

Ex01. setCookie

setCookie.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>
<%
//1. 쿠키 생성
Cookie c = new Cookie("id", "test");

//2.유효기간 설정
c.setMaxAge(60*1); //1분

//3.클라이언트에 쿠키 전송
response.addCookie(c);

//4.쿠키를 생성하여 클라리언트에 전송
response.addCookie(new Cookie("pwd", "1234"));
response.addCookie(new Cookie("age", "26"));

%>
<h3>쿠키 설정</h3>
</body>
</html>

실행화면

 

getCookie.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>
<h2>클라이언트에서 가져온 쿠키 정보</h2>
<%
Cookie[] cookies = request.getCookies();
for(Cookie a : cookies){
	out.print(a.getName() + " : " + a.getValue() + "<br>");
}
%>
</body>
</html>

실행화면
1분 후 새로고침 후

c.setMaxAge(60*1); 로 유효시간을 설정해 보았으므로 1분 후에 새로 고침을 하면 id의 정보값이 사라지는 것을 볼 수 있다.  

 

 


Ex02. removeCookie

removeCookie.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 c = new Cookie("id", "");
	response.addCookie(c);
%>
<h2>id 쿠키가 삭제됨</h2>
<a href="getCookie.jsp">쿠키 삭제를 확인하세요</a>
</body>
</html>

setCookie.jsp로 쿠키를 세팅해 준 뒤에 removeCookie.jsp를 실행하여 id를 삭제하고 a 링크를 클릭하여 해당 페이지를 확인해보자.

실행화면
a링크를 클릭하여 이동한 화면

728x90
반응형

댓글