Cookie(쿠키)는 클라이언트 측(웹 브라우저)에 저장되는 작은 데이터입니다. 웹 애플리케이션이 사용자의 상태를 유지하거나 특정 정보를 기억하기 위해 사용합니다.
쿠키는 클라이언트와 서버 간의 비연결적 상태(stateless)를 보완하기 위해 고안되었습니다.
import org.springframework.http.ResponseCookie;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
@RestController
public class CookieController {
@GetMapping("/set-cookie")
public ResponseEntity<String> setCookie() {
ResponseCookie cookie = ResponseCookie.from("userId", "12345")
.httpOnly(true)
.path("/")
.maxAge(3600)
.build();
return ResponseEntity.ok()
.header("Set-Cookie", cookie.toString())
.body("Cookie Set!");
}
@GetMapping("/get-cookie")
public String getCookie(HttpServletRequest request) {
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if ("userId".equals(cookie.getName())) {
return "Found cookie: " + cookie.getValue();
}
}
}
return "No cookie found.";
}
}
Session(세션)은 서버에서 관리되는 사용자 상태 정보입니다.
클라이언트가 서버와 상호작용하는 동안의 데이터를 저장하며, 주로 사용자 인증 상태를 유지하기 위해 사용됩니다.
Spring에서는 HttpSession을 사용하여 세션 데이터를 쉽게 관리할 수 있습니다.
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpSession;
@RestController
public class SessionController {
@GetMapping("/set-session")
public String setSession(HttpSession session) {
session.setAttribute("username", "john_doe");
return "Session set for username: john_doe";
}
@GetMapping("/get-session")
public String getSession(HttpSession session) {
String username = (String) session.getAttribute("username");
return username != null ? "Session username: " + username : "No session found.";
}
}
| 항목 | Cookie | Session |
|---|---|---|
| 저장 위치 | 클라이언트(브라우저) | 서버 |
| 보안성 | 상대적으로 낮음 | 상대적으로 높음 |
| 데이터 용량 제한 | 4KB 이내 | 제한 없음 (서버 메모리 용량 의존) |
| 데이터 유지 | 만료 시간 설정 가능 | 세션 만료 시 삭제 |
| 사용 예시 | 사용자 설정 저장, 로그인 유지 | 사용자 인증, 민감 데이터 관리 |
쿠키와 세션은 보통 조합해서 사용됩니다.
// 브라우저에 저장되는 쿠키
Set-Cookie: JSESSIONID=12345ABCD; Path=/; HttpOnly; Secure
ResponseCookie와 HttpSession을 활용하면 손쉽게 상태 정보를 관리할 수 있음을 알게 되었습니다. HttpOnly 및 Secure 옵션을 설정하고, 세션은 일정 시간 이후 만료되도록 구성해야 함을 배웠습니다.