https://jakarta.ee/specifications/servlet/5.0/apidocs/jakarta/servlet/http/cookie
Cookie)와 응답 헤더(Set-Cookie)를 통해 서버와 주고받음.Set-Cookie를 추가하여 쿠키 전달.sequenceDiagram
participant Client as 클라이언트 (브라우저)
participant Server as 서버
Client->>Server: HTTP 요청 (로그인)
Server-->>Client: HTTP 응답 + Set-Cookie (sessionId=abc123)
Client->>Server: HTTP 요청 + Cookie (sessionId=abc123)
Server-->>Client: 사용자 상태 확인 및 응답
Set-Cookie: sessionId=abc123; Max-Age=3600; Path=/; HttpOnly; Secure
Cookie: sessionId=abc123
@GetMapping("/set-cookie")
public ResponseEntity<String> setCookie(HttpServletResponse response) {
Cookie cookie = new Cookie("username", "홍길동");
cookie.setMaxAge(7 * 24 * 60 * 60); // 7일 유지
cookie.setPath("/"); // 모든 경로에서 유효
cookie.setHttpOnly(true); // JavaScript 접근 불가
cookie.setSecure(true); // HTTPS에서만 전송
response.addCookie(cookie);
return ResponseEntity.ok("Cookie set!");
}
@GetMapping("/get-cookie")
public ResponseEntity<String> getCookie(@CookieValue(value = "username", defaultValue = "Guest") String username) {
return ResponseEntity.ok("Hello, " + username);
}
@GetMapping("/get-all-cookies")
public ResponseEntity<String> getAllCookies(HttpServletRequest request) {
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
System.out.println(cookie.getName() + " = " + cookie.getValue());
}
}
return ResponseEntity.ok("Cookies printed in server logs.");
}
쿠키는 클라이언트(브라우저)에 저장된 데이터이므로 삭제하려면 쿠키의 수명을 설정하거나, 서버에서 동일한 이름과 경로로 만료된 쿠키를 설정해야 합니다.
Max-Age를 0으로 설정하면 브라우저는 즉시 쿠키를 삭제합니다.Expires를 과거 시간으로 설정하면 삭제됩니다.HttpServletResponse로 쿠키 삭제@GetMapping("/delete-cookie")
public ResponseEntity<String> deleteCookie(HttpServletResponse response) {
Cookie cookie = new Cookie("username", null); // 값은 null로 설정
cookie.setMaxAge(0); // 즉시 만료
cookie.setPath("/"); // 경로 일치
response.addCookie(cookie);
return ResponseEntity.ok("Cookie deleted");
}
HttpServletRequest로 쿠키 확인 후 삭제@GetMapping("/delete-specific-cookie")
public ResponseEntity<String> deleteSpecificCookie(HttpServletRequest request, HttpServletResponse response) {
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if ("username".equals(cookie.getName())) {
Cookie deleteCookie = new Cookie("username", null);
deleteCookie.setMaxAge(0); // 즉시 만료
deleteCookie.setPath("/");
response.addCookie(deleteCookie);
}
}
}
return ResponseEntity.ok("Specific cookie deleted");
}
클라이언트 측에서 JavaScript를 사용해 쿠키를 삭제할 수도 있습니다. 단, HttpOnly가 설정된 쿠키는 JavaScript로 삭제할 수 없습니다.
// 쿠키 삭제
document.cookie = "username=; Max-Age=0; path=/;";
HttpOnly, Secure 속성이 설정된 쿠키는 서버에서만 삭제 가능하며, JavaScript로 삭제할 수 없습니다.Max-Age=0 또는 Expires를 과거로 설정.HttpOnly, Secure 속성이 설정된 쿠키는 서버에서만 삭제 가능.Strict: 쿠키는 동일한 사이트에서만 전송.Lax: 대부분의 크로스 사이트 요청에서 쿠키가 전송되지 않음.None: 크로스 사이트 요청에서도 쿠키 전송(단, Secure 필요).Cookie cookie = new Cookie("sessionId", "abc123");
cookie.setHttpOnly(true);
cookie.setSecure(true);
cookie.setPath("/");
cookie.setMaxAge(3600); // 1시간
response.addCookie(cookie);
| 장점 | 단점 |
|---|---|
| 클라이언트 상태 정보를 쉽게 저장하고 관리 가능 | 용량 제한(4KB) |
| 서버 부하 감소 (상태 정보를 서버에 저장하지 않음) | 클라이언트에서 조작 가능 (보안 문제 발생 가능) |
| 수명 설정 가능 (짧거나 긴 시간 동안 유지 가능) | HTTP를 통해 전송되므로 도청 위험 (HTTPS 필요) |
| 브라우저 간 호환성 높음 | 쿠키의 잘못된 설정으로 보안 문제가 발생할 가능성 있음 |
| 항목 | 쿠키(Cookie) | 세션(Session) |
|---|---|---|
| 저장 위치 | 클라이언트(브라우저) | 서버 |
| 데이터 용량 | 4KB 제한 | 서버 메모리에 의존 |
| 보안 | 클라이언트에서 쉽게 조작 가능 (HTTPS로 전송 암호화 필요) | 클라이언트에서 직접 접근 불가, 서버가 관리 |
| 속도 | 빠름 (클라이언트에 저장) | 상대적으로 느림 (매 요청마다 서버 확인 필요) |
| 유지 시간 | 만료 시간 설정 가능, 브라우저 종료 시 삭제 가능 | 세션 타임아웃 설정 가능 |
| 사용 사례 | 사용자의 기본 설정 저장, 로그인 상태 유지 | 사용자 인증, 장바구니 데이터, 민감한 데이터 처리 |
flowchart TD
A["login_form.jsp (아이디와 비밀번호 입력)"]
B["login_ok.jsp (로그인 검사)"]
C["login_complete.jsp (로그인 완료 페이지 - 쿠키 검사)"]
A -->|id & password 입력| B
B -->|검사 성공| C
C -->|쿠키 유효| C
C -->|쿠키 무효| A
B -->|검사 실패| A