본문 바로가기

콩's EDUCATION/콩's JSP&SERVLET

쿠키(Cookie) 보내고 보여주고 수정하고 삭제하기

makeCookie.jsp

 

<%@page import="java.net.URLEncoder"%>
<%@ page contentType="text/html; charset=utf-8"
    %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>쿠키 Cookie</title>
</head>
<body>
<%
Cookie cookie = new Cookie("name",URLEncoder.encode("콩쓰","utf-8"));
response.addCookie(cookie);
%>
<center><h3>쿠키 생성</h3></center>
쿠키를 생성해서 응답으로 보냄<br>
</body>
</html>

 

viewCookie.jsp

 

<%@page import="java.net.URLDecoder"%>
<%@page import="java.net.URLEncoder"%>
<%@ page contentType="text/html; charset=utf-8"
    %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>쿠키 Cookie View</title>
</head>
<body>
<%
Cookie[] cookies = request.getCookies();
if(cookies!=null && cookies.length>0){
 for(int i=0;i<cookies.length;i++){
%>
<%=cookies[i].getName()%> :
<%=URLDecoder.decode(cookies[i].getValue(),"utf-8") %><br>
<% }
}else{
%>
쿠키가 존재하지 않습니다.
<%
}
%>

<h3>쿠키 보여주기</h3>
쿠키를 생성해서 응답으로 보냄<br>
</body>
</html>

 

[결과]

 

 

modifyCookie.jsp

 

<%@page import="java.net.URLDecoder"%>
<%@page import="java.net.URLEncoder"%>
<%@ page contentType="text/html; charset=utf-8"
    %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>쿠키 Cookie View</title>
</head>
<body>
<%
Cookie[] cookies = request.getCookies();
if(cookies!=null && cookies.length>0){
 for(int i=0;i<cookies.length;i++){
  if(cookies[i].getName().equals("name")){
   Cookie cookie = new Cookie("name", URLEncoder.encode("JSP프로그래밍","utf-8"));
   response.addCookie(cookie);
  }
 %>
쿠키가 NAME 변경하기
<%
}
}else{
%>
쿠키가 존재하지 않습니다.
<%
}
%>

<h3>쿠키 보여주기</h3>
쿠키를 생성해서 응답으로 보냄<br>
<a href= "./viewCookie.jsp">viewCookie</a>
</body>
</html>

deleteCookie.jsp

 

<%@page import="java.net.URLDecoder"%>
<%@page import="java.net.URLEncoder"%>
<%@ page contentType="text/html; charset=utf-8"
    %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>쿠키 Cookie View</title>
</head>
<body>
<%
Cookie[] cookies = request.getCookies();
if(cookies!=null && cookies.length>0){
 for(int i=0;i<cookies.length;i++){
  if(cookies[i].getName().equals("name")){
   Cookie cookie = new Cookie("name","");
   cookie.setMaxAge(0);
   response.addCookie(cookie);
  }
  }
%>
쿠키중 NAME 키의 값을 삭제하였습니다.
<%
}else{
%>
쿠키가 존재하지 않습니다.
<%
}
%>

<h3>쿠키 보여주기</h3>
쿠키를 생성해서 응답으로 보냄<br>
<a href= "./viewCookie.jsp">viewCookie</a>
</body>
</html>