08.Cookie

이현주·2023년 9월 13일
0

Servlet

목록 보기
9/10

1.클라이언트 측에 저장되는 정보를 의미한다.
2. 보안에는 취약하므로 개인 정보 같은 민감 정보는 저장하지 않는다.

[NewFile.html]
설정한 쿠키값을 확인해 value가 true 가 아니라면 팝업창을 띄우지 않는다.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://cdn.jsdelivr.net/npm/js-cookie@3.0.5/dist/js.cookie.min.js"></script>
<script>
  // do_not_open_today 쿠키값 확인
  var popupCookie = Cookies.get('do_not_open_today');  //해당 쿠키가 없으면 undefined
  
  if(popupCookie !== 'true'){
  	window.open('popup.html','','width=300,height=500,top=100,left=100');
  }
  
</script>
</head>
<body>

  <div>
    화면 
  </div>

</body>
</html>

[popup.html]
팝업화면

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://cdn.jsdelivr.net/npm/js-cookie@3.0.5/dist/js.cookie.min.js"></script>
<script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
<script>

</script>
</head>
<body>

  <div>
    <h1>팝업화면</h1>
  </div>
  
  <div>
    <input type="checkbox" id="do_not_open_today">
    <label for="do_not_open_today">오늘 더 이상 열지 않기</label>
    <button type="button" id="btn_close">닫기</button>
  </div>
  <script>
  
  //오늘 더 이상 열지 않기를 체크한 경우
  // do_not_open_today 쿠키를 1일 동안 모든 경로("/")에서 사용할 수 있도록 저장한다.
  
  $('#btn_close').click(function() {
		if($('#do_not_open_today').is(':checked'))  //if($('#do_not_open_today').prop('checked'))  
  	{
		 Cookies.set('do_not_open_today','true',{expires:1 ,path:'/'});  //쿠키 저장 
  	}
  	
		window.close(); // 현재 창 닫기
		
	})
  
  
  </script>
</body>
</html>

[cookie1.java]

쿠키 만들기

	Cookie cookie1 =new Cookie("name","곽두팔");
		Cookie cookie2 =new Cookie("age","10000"); // 모든 쿠키 값은 String 타입으로 저장한다.
		Cookie cookie3 = new Cookie("address",URLEncoder.encode("조선천지에 있을수 없는곳","UTF-8"));//공백은 유효하지 않은 문자이므로 인코딩이 필요하다.
        

쿠키가 저장될 경로 설정하기

(생략하면 컨텍스트패스 경로에 저장된다.)

	cookie1.setPath("/servlet");			  // 컨텍스트패스 : request.getContextPath()
		cookie2.setPath("/servlet/cookie1"); // 서블릿경로	 : request.getRequestURI()	
											// cookie3 은 경로 설정을 생략했으므로 컨텍스트패스에 저장된다.

쿠키가 유지되는 시간 설정하기

(생략하면 세션 쿠키가 된다. 브라우저를 닫으면 지워진다.)

cookie.setMaxAge(60*60); 	//1시간
cookie.setMaxAge(60*60*24*7)//7일
							// cookie3은 시간 설정을 생략했으므로 세션 쿠키가 된다.

쿠키를 브라우저에 저장하기

(응답으로 처리한다.)

response.addCookie(cookie1);
response.addCookie(cookie2);
response.addCookie(cookie3);

cookie2 서블릿으로 redirect 이동

response.sendRedirect("/servlet/cookie2");

[cookie2.java]

요청한 곳의 모든 쿠키 가져오기

(골라서 가져올 수 없다.)

Cookie[] cookies=request.getCookies();

쿠키 확인하기

if(cookies !=null)
{
for(int i=0;i<cookies.length;i++)
	{
//쿠키이름
    String name =cookies[i].getName();
//쿠키 값
String value = URLDecoder.decode(cookies[i].getValue(),"UTF-8");
//쿠키 경로
String path=cookies[i].getPath();
				
//쿠키 유지 시간
int expire=cookies[i].getMaxAge();
				
				
System.out.println(name+","+value+","+path+","+expire);
	}
}

쿠키 삭제하기

(같은 이름의 쿠키를 만든 뒤 쿠키 유지시간을 0으로 설정하고 저장한다(덮어쓰기한다.))

Cookie cookie = new Cookie("name","값은아무의미가없다");
		cookie.setMaxAge(0);
		response.addCookie(cookie);

오늘 더이상 열지 않기 체크시 설정한 시간만큼 팝업창이 나타나지 않는다.
크롬개발자도구>application>Cookies

Value를 true가 아닌 다른 값을 넣으면 설정한 시간이 경과하지 않아도 팝업창이 다시 활성화 된다.

profile
졸려요

0개의 댓글