1. JSP 활용하여 쿠키 생성하기
- SetCookie.java
package test.controller;
import java.io.IOException;
import java.net.URLEncoder;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/cookie")
public class SetCookie extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie cookie = new Cookie("coo", URLEncoder.encode("쿠키 테스트", "utf-8"));
cookie.setMaxAge(60 * 60 * 24);
resp.addCookie(cookie);
}
}
2. 생성된 쿠키 확인하기
- cookie.jsp
<%@page import="java.net.URLDecoder"%>
<%@ 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(Cookie cookie : cookies) {
out.print(cookie.getName() + "<br>");
out.print(URLDecoder.decode(cookie.getValue(), "utf-8") + "<br>");
}
%>
</body>
</html>