JAVA/JSP

[JSP] 쿠키(Cookies)

아잠만_ 2024. 7. 18. 14:13

쿠키 가져오기

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="/js/jquery.min.js"></script>
<script>
$(function(){
	$('#btnCookieDel').on('click',function(){
		location.href="/ch14/cookies03.jsp"
	})
})
</script>
</head>
<body>
<%
	// 클라이언트에 저장한 모든 쿠키 객체를 가져옴
	Cookie[] cookies = request.getCookies();

	for(int i=0; i<cookies.length; i++){
		out.print("<p>"+cookies[i].getName() + " : " + cookies[i].getValue() + "</p>" );
	}
	out.print("<hr />");
	out.print("<p>세션 아이디 : "+session.getId()+"</p>");

%>
<!-- 
   요청URI : cookie01_process.jsp
   요청파라미터 : {id=a001,passwd=java}
   요청방식 : post
    -->
	<form action="cookies01_process.jsp" method="post">
		<p>아이디 : <input type="text" name="id" placeholder="아이디"></p>
		<p>비밀번호 : <input type="password" name="pw" placeholder="비밀번호"></p>
		<p><input type="submit" value="전송"></p>
		<p><input id="btnCookieDel" type="button" value="쿠키 삭제"></p>
	</form>
</body>
</html>

쿠키 저장

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" href="/css/bootstrap.min.css">
</head>
<body>
<!-- 
   요청URI : cookie01_process.jsp
   요청파라미터 : {id=a001,passwd=java}
   요청방식 : post
    -->
	<!-- 쿠키 생성
	Cookie 클래스를 사용하여 쿠키를 생성.
	쿠키를 생성한 후에는 꼭 response 내장 객체의 addCookies()메서드로 쿠키를 설정해야 함 -->
	<%
		String id = request.getParameter("id");
		String pw = request.getParameter("pw");
	
		Cookie cookie_id = new Cookie("id",id);
		Cookie cookie_pw = new Cookie("pw",pw);
		response.addCookie(cookie_id);
		response.addCookie(cookie_pw);
	%>
	<a href="/ch14/cookies01.jsp" class="btn btn-primary">되돌아가기</a>
</body>
</html>

쿠키 삭제

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%
		//Cookie cookie_id = new Cookie("userId",user_id);
	//Cookie cookie_pw = new Cookie("userPd",user_pw);
	//+ JSESSIONID
	//요청 시 함께 툭툭 던져지는 request객체 안에 있는 쿠키들을 확인해보자
	Cookie[] cookies = request.getCookies();
	
	//현재 설정된 쿠키의 개수?
	out.print("현재 설정된 쿠키의 개수 : " + cookies.length + "<br />");
	out.print("<hr />");
	for (int i = 0; i < cookies.length; i++) {//i : 0, 1, 2
		out.print("<p>쿠키[" + i + "] : " + cookies[i] + "</p>");
		// 쿠키 속성 이름
		out.print("<p>설정된 쿠키의 속성 이름[" + i + "] : " + cookies[i].getName() + "</p>");
		//쿠키 속성 값
		out.print("<p>설정된 쿠키의 값[" + i + "] : " + cookies[i].getValue() + "</p>");
		out.print("<hr />");
	
		//쿠키 삭제
		/*
		    쿠키를 삭제하는 기능은 별도로 없음.
		    쿠키를 더 유지할 필요가 없으면 쿠키의 유효 기간을 만료하면 됨
		    쿠키의 유효 기간을 결정하는 setMaxAge() 메소드에 유효 기간을 0으로 설정하여
		 쿠키를 삭제할 수 있음
		*/
		cookies[i].setMaxAge(0);
		response.addCookie(cookies[i]);
	}
	out.print("<p>세션ID : " + session.getId() + "</p>");
%>
<script>
setTimeout(function(){
	location.href="/ch14/cookies01.jsp";
},5000);
</script>