쿠키(CooKie)

조윤후·2021년 7월 29일

쿠키란 ?

웹브라우저에서 서버로 데이터를 요청하면, 서버측에서 로직을 수행한 후 데이터를 웹브라우저에 응답한다. 그리고, 서버는 웹브라우저와의 관계를 종료한다. 이렇게 웹브라우저에 응답 후 관계를 끊는 것은 http프로토콜의 특징이다. 연결이 끊어졌을때 정보를 지속적으로 유지하기 위한 수단으로 쿠키라는 방식을 사용한다. 쿠키는 서버에서 생성하여, 서버가 아닌 클라이언트측에 특정 정보를 저장한다. 그리고 서버에 요청할 때 마다 쿠키의 속성값을 참조 또는 변경 할 수 있습니다.

쿠키는 4kb로 용량이 제한적이며, 300개까지 데이터 정보를 가질 수 있다.

쿠키 관련 메서드

  • setMaxage() : 쿠키 유효기간을 설정한다.
  • setpath() : 쿠키의 사용 휴효 디렉토리를 설정한다.
  • setValue() : 쿠키의 값을 설정한다.
  • setVersion() : 쿠키버전을 설정한다.
  • getMaxAge() : 쿠키 유효기간 정보를 얻습니다.
  • getName : 쿠키의 이름을 얻는다.
  • getPath() : 쿠키의 유효 디렉토리 정보를 얻어온다.
  • getValue() : 쿠키의 값을 얻어온다.
  • getVersion() : 쿠키 버전을 얻는다.

쿠키사용법

1. 쿠키 생성하기

<%@ 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 cookie = new Cookie("cookieN","cookieV"); //쿠키의 이름과 value를 지정해준다.
	cookie.setMaxAge(60 * 60); //
	response.addCookie(cookie);
%>

 <a href="cookieget.jsp">쿠키가지고오기</a>
</body>
</html>

2. 쿠키 사용하기

<%@ 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[] cookies = request.getCookies();
	
	for (int i = 0; i < cookies.length; i++) {
		String str = cookies[i].getName();
		if (str.equals("cookieN")) {
			out.println("Cookies[i].getName :" + cookies[i].getName() + "</br>");
			out.println("Cookies[i].getValue : " + cookies[i].getValue());
			cookies[i].setMaxAge(0); //쿠키삭제
			response.addCookie(cookies[i]);
		}
	}

%>

 <a href="cookietest.jsp">쿠키테스트</a>
</body>
</html>

3. 삭제된 쿠키 검증하기

<%@ 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[] cookies = request.getCookies();
	
	if (cookies != null) {
		for (int i = 0; i < cookies.length; i++) {
			out.println("cookie : " + cookies[i].getName());	
		}
	}
%>

</body>
</html>
profile
공부하며 예제풀이 정리

0개의 댓글