데이터 전송
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<title>Cookie</title>
</head>
<body>
<form method="post" action="cookie01_process.jsp">
<p>아 이 디 : <input type="text" name="id" /></p>
<p>비밀번호 : <input type="text" name="passwd" /></p>
<p><input type="submit" value="전송" /></p>
</form>
</body>
</html>
쿠키객체 생성, 쿠키에 데이터 저장
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<title>Cookie</title>
</head>
<body>
<%
//?id=admin&passwd=1234
String user_id = request.getParameter("id");
String user_pw = request.getParameter("passwd");
if(user_id.equals("admin")&&user_pw.equals("1234")){
//Cookie 객체 생성
Cookie cookie_id = new Cookie("userID", user_id);
Cookie cookie_pw = new Cookie("userPW", user_pw);
response.addCookie(cookie_id);
response.addCookie(cookie_pw);
out.print("쿠키 생성 성공!");
out.print(user_id + "님 환영합니다.");
}
%>
</body>
</html>
쿠키에 저장된 정보 얻어오기
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
//쿠키 정보를 얻어오기
Cookie[] cookies = request.getCookies();
for(int i=0; i<cookies.length;i++){
out.print("설정된 쿠키의 속성명[" + i + "] : "+ cookies[i].getName() + "<br>");
out.print("설정된 쿠키의 속성값[" + i + "] : "+ cookies[i].getValue()+ "<br>");
out.print("================================<br />");
}
%>
쿠키 삭제하기
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<title>Cookie</title>
</head>
<body>
<%
Cookie[] cookies = request.getCookies();
for(int i =0; i< cookies.length; i++){
//쿠키 삭제 : 유효 기간을 0으로 설정
cookies[i].setMaxAge(0);
response.addCookie(cookies[i]);
}
response.sendRedirect("cookie02.jsp");
%>
</body>
</html>