쿠키(Cookie)

  • HTTP 프로토콜은 웹 브라우저(클라이언트)의 요청에 대한 응답을 하고 나면 해당 클라이언트와의 연결을 지속하지 않음
  • 상태가 없는 프로토콜을 위해 상태를 지속시키기 위한 방법
  • 정보를 웹 브라우저에 저장
makeCookie.jsp 파일

<%
	Cookie cookie = new Cookie("id", "user01"); // id키에 사용자ID 'user01'을 저장
	cookie.setMaxAge(60*2); // 단위 초. 가시성 좋게
	response.addCookie(cookie); // response객체에 쿠키 추가. 서버측에 결과를 클라이언트에게 보내질때 response객체의 내용이 전해짐
	
	out.println("쿠키가 생성됨");
%>    


<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<form method="post" action="useCookie.jsp">
		<dl>
			<dd><input type="submit" value="쿠키확인"></dd>
		</dl>
	</form>
	<form method="post" action="removeCookie.jsp">
		<dl>
			<dd><input type="submit" value="쿠키소멸"></dd>
		</dl>
	</form>
</body>
</html>
useCookie.jsp 파일

<%
	// 브라우저는 사이트를 재방문시 쿠키를 가지고 서버측에 접속하게 된다
	Cookie[] cookies = request.getCookies(); //클라이언트에게 생성해 준 쿠키를 읽는 작업
	if(cookies != null){
		for(int i=0; i<cookies.length; i++){
			if(cookies[i].getName().equals("id")) {
				out.println("쿠키 이름 : " + cookies[i].getName());
				out.println(", 쿠키 값 : " + cookies[i].getValue());
			}
		}
	}
%>
removeCookie.jsp 파일

<%
	Cookie cookie = new Cookie("id", null); // id키에 사용자ID 'user01'을 저장
	cookie.setMaxAge(0); // 단위 초. 가시성 좋게
	response.addCookie(cookie); // response객체에 쿠키 추가. 서버측에 결과를 클라이언트에게 보내질때 response객체의 내용이 전해짐
	
	out.println("쿠키가 소멸됨");
%>

태그:

카테고리:

업데이트:

댓글남기기