수업 내용/[JSP] JSP

[JSP] 06. cookie

프롯 2023. 5. 23. 18:37

쿠키란 사용자가 웹 브라우저의 방문 기록을 저장해 놓은 데이터이다.

 

세션과의 차이점은 쿠키는 클라이언트의 개인 기기에 저장되며 서버를 사용하지 않는다.

따라서 쿠키는 사용자가 필요에 따라 유지시킬 수도, 삭제할 수 있다.

 

세션은 서버에 저장되는 데이터 이다. 

따라서 더 빠르고, 보안 면에서 우수하다.

 

하지만 모든 데이터를 세션에 저장할 시 서버에 너무 많은 데이터가 몰려 속도가 느려질 수 있으므로 쿠키와 구분하여 저장한다.

 

 

 

쿠키 생성

<%@page import="java.net.URLDecoder"%>
<%@page import="java.net.URLEncoder"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    
    <%
    //1. 쿠키 만들기 (서버로 쿠키 만들기)
    //Cookie ciikue = new Cookie("쿠키 이름", "쿠키 값");
    Cookie cookie = new Cookie("id", "admin");
    
    //쿠키 유효시간 설정 (1일)
    cookie.setMaxAge(60* 60* 24);
    //"쿠키 값"에 공백, 콤마, 괄호 등을 저장하려면 인코딩을 해야 함
    Cookie bisket = new Cookie("name", URLEncoder.encode("김씨", "utf-8"));
    //bisket의 유호시간을 20분으로 설정
    bisket.setMaxAge(60 * 20);
    
    //만든 쿠키를 쿠키 저장소에 저장
    response.addCookie(cookie);
    response.addCookie(bisket);
    
    
    %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>
		쿠키 1 이름 : <%=cookie.getName() %>
		쿠키 1 값 : <%=cookie.getValue() %>
		
		쿠키 2 이름 : <%=cookie.getName() %>
		쿠키 2 값 : <%=URLDecoder.decode(bisket.getValue(), "utf-8") %>
	</h1>
</body>
</html>

 

 

쿠키 저장되있는지 확인

<%@page import="java.net.URLDecoder"%>
<%@ 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[] cookieBox = request.getCookies();
		
		if(cookieBox != null && cookieBox.length >0){
			for(int i = 0; i<cookieBox.length; i++){
				out.print("쿠키 이름 : " + cookieBox[i].getName() + "<br/>");
				out.print("쿠키 값 : "  + URLDecoder.decode(cookieBox[i].getValue(), "utf-8"));
			}
		}
		else{
			out.print("쿠키가 존재하지 않습니다.");
		}
	%>
</body>
</html>

 

 

 

쿠키값 변경하기

쿠키 값 변경은 덮어쓰기이다. 먼저 쿠키가 존재하는지 확인 필요

 

<%@page import="java.net.URLEncoder"%>
<%@page import="java.net.URLDecoder"%>
<%@ 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. 이름이 name인 쿠키의 값을 "마이클 조던"으로 변경
		2. 유효 시간을 15일로 변경
		3. 쿠키 저장소에 저장
	 -->
	 <%
	 Cookie[] cookieBox = request.getCookies();
	 
	 	if(cookieBox != null && cookieBox.length >0){
			for(int i = 0; i<cookieBox.length; i++){
				if(cookieBox[i].getName().equals("name")){
					Cookie bisket = new Cookie("name", URLEncoder.encode("마이클 조던", "utf-8"));
					bisket.setMaxAge(60* 60* 24 * 15);
					response.addCookie(bisket);
					out.print("쿠키 값을 변경하였습니다.");
				}
			}
		}
		else{
			out.print("해당 쿠키가 존재하지 않습니다.");
		}
	 
	 	Cookie[] cookieBoxx = request.getCookies();
		if(cookieBoxx != null && cookieBoxx.length >0){
			for(int i = 0; i<cookieBoxx.length; i++){
				out.print("쿠키 이름 : " + cookieBoxx[i].getName() + "<br/>");
				out.print("쿠키 값 : "  + URLDecoder.decode(cookieBoxx[i].getValue(), "utf-8"));
			}
		}
		else{
			out.print("쿠키가 존재하지 않습니다.");
		}
	 %>
	 
</body>
</html>

 

 

 

쿠키 삭제하기

쿠키 삭제는 기존 쿠키의 유효 시간을 0 으로 한다.

<%@page import="java.net.URLDecoder"%>
<%@page import="java.net.URLEncoder"%>
<%@ 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>
	<!-- 
		쿠키 삭제는 기존 쿠키의 유효 시간을 0 으로 한다.
		
		1. 이름이 name인 쿠키 삭제
	 -->
	 <%
	 Cookie[] cookieBox = request.getCookies();
	 
	 if(cookieBox != null && cookieBox.length >0){
			for(int i = 0; i<cookieBox.length; i++){
				if(cookieBox[i].getName().equals("name")){
					Cookie bisket = new Cookie("name", URLEncoder.encode("마이클 조던", "utf-8"));
					bisket.setMaxAge(0);
					response.addCookie(bisket);
					out.print("쿠키가 삭제되었습니다.");
				}
			}
		}
		else{
			out.print("해당 쿠키가 존재하지 않습니다.");
		}
	 
	 
	 	Cookie[] cookieBoxx = request.getCookies();
		if(cookieBoxx != null && cookieBoxx.length >0){
			for(int i = 0; i<cookieBoxx.length; i++){
				out.print("쿠키 이름 : " + cookieBoxx[i].getName() + "<br/>");
				out.print("쿠키 값 : "  + URLDecoder.decode(cookieBoxx[i].getValue(), "utf-8"));
			}
		}
		else{
			out.print("쿠키가 존재하지 않습니다.");
		}
	 %>
</body>
</html>