Java로 쿠키 생성하기

✒️ 2025-06-24 10:53 내용 수정


쿠키
저장 위치 클라이언트
종료 시점 쿠키 생성 시 만료일 설정
설정이 없다면 웹 브라우저 종료 시 소멸
데이터 크기 4KB 제한
리소스 클라이언트의 리소스
보안 클라이언트에 저장되어 사용자 변경이 가능함.
보안에 취약
목적 상태 유지, 개인화

// cookie 생성
Cookie cookie = new Cookie("name", "value");

// cookie 전송
response.addCookie(cookie);
Cookie cookie = new Cookie("name", "value");
cookie.setMaxAge(0); // 즉시 제거
설명
양수 해당 초만큼 유지
0 즉시 삭제
음수 기본값
브라우저 종료 시 삭제

메서드

메서드 설명
String getComment() 쿠키에 대한 설명 반환
String getDomain() 쿠키에 대한 유효한 도메인 정보 반환
int getMaxAge() 쿠키의 유효 기간 반환. 초 단위
String getName() 쿠키의 이름 반환
String getPath() 쿠키의 유효한 디렉터리 정보 반환
boolean getSecure() 쿠키의 보안 설정 반환
String getValue() 쿠키의 값 반환
int getVersion() 쿠키의 버전 반환
setComment(String comm) 쿠키에 대한 설명 지정
setDomain(String domain) 쿠키에 유효한 도메인 설정
setMaxAge(int age) 쿠키의 유효 기간 설정. 초 단위
setPath(String path) 쿠키가 적용되는 경로 지정
setSecure(boolean sec) 쿠키의 보안 설정
setValue(String value) 쿠키의 값 설정
setVersion(int version) 쿠키의 버전 설정
setHttpOnly(boolean mode) 쿠키의 JavaScript 접근 여부 설정
true : 접근 차단
false : 접근 가능

예제

1. 쿠키 생성 및 저장

@WebServlet("/cookie")
public class SetCookieAction extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		// 쿠키 생성
		Cookie cookie = new Cookie("param1", "asdf");
		
		// 쿠키 기한 정하기
		cookie.setMaxAge(3600*24*7); // 일주일

		// 쿠키 유효 범위
		cookie.setPath("/");

		// 쿠키 추가 - 필수!
		response.addCookie(cookie);

		// 쿠키 전송
		response.sendRedirect("ex01_Cookie.jsp");
	}
}
<%@ 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>
	쿠키 저장 완료<br>
	쿠키 이름 : ${cookie.param1.name} <br>
	쿠키 내용 : ${cookie.param1.value} <br>
</body>
</html>

cookie.png

2. 쿠키 읽기

@WebServlet("/cookie")
public class SetCookieAction extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		// 쿠키 객체 얻기
		// 쿠키가 여러 개 일 때는 배열로 가져옴
		Cookie[] cookies = request.getCookies();
		
		for(Cookie c : cookies) {
			System.out.println("이름 : " + c.getName());
			System.out.println("값 : " + c.getValue());
			System.out.println("-----------------");
		}
	}
}

cookie 2.png

3. 쿠키 제거

<%@ page import="javax.servlet.http.Cookie" %>
<%
Cookie[] cookies = request.getCookies();
	if (cookies != null) {
		for (Cookie c : cookies) {
			// 특정 이름의 쿠키 검색
			if ("userId".equals(c.getName())) {
				c.setMaxAge(0);        // 즉시 만료
				c.setPath("/"); // 반드시 처음 지정 경로와 동일하게
			}
	}
}
%>
<p>쿠키를 삭제했습니다.</p>