요약 한 줄
쿠키는 브라우저가 들고 다니는 작은 메모, 세션은 서버가 기억하고 쿠키(JSESSIONID)로 찾아오는 저장공간입니다. 로그인/장바구니는 보통 “세션”으로, “아이디 기억하기”는 “쿠키”로!
구분 쿠키(Cookie) 세션(Session)
| 저장 위치 | 클라이언트(브라우저) | 서버(메모리/세션 저장소) |
| 식별 방식 | Cookie 헤더로 키-값 전달 | JSESSIONID 쿠키로 세션을 조회 |
| 수명 | Max-Age/Expires로 지정(영구/단기) | 유휴 시간(예: 30분) 지나면 만료 |
| 용도 | 아이디 기억, 다크모드, A/B 실험 등 | 로그인 상태, 장바구니, 권한 정보 |
| 보안 | 탈취 위험 → HttpOnly/Secure/SameSite 필수 | 서버 보안 중심, 세션 고정 공격 주의 |
| 용량 | 도메인당 수 KB 수준 | 서버 자원 사용(사용자 수↑ = 메모리↑) |
포인트: “민감한 정보는 쿠키에 절대 직접 저장하지 말고, 세션에 저장하고 식별용 세션ID만 쿠키로!”
// 로그인 검증 이후
HttpSession session = req.getSession(); // 없으면 생성
session.setAttribute("loginUser", user); // 사용자 객체/ID 등
session.setMaxInactiveInterval(30 * 60); // 30분 비활성 시 만료
// 필요 시 세션 고정 방지: 새 세션 발급
session.invalidate();
HttpSession newSession = req.getSession(true);
newSession.setAttribute("loginUser", user);HttpSession session = req.getSession(false); // 있으면 가져오고, 없으면 null
if (session != null) {
session.invalidate(); // 세션 파기
}
resp.sendRedirect("/"); // 홈으로
6-3. “아이디 기억하기” 쿠키
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import jakarta.servlet.http.Cookie;
// 로그인 폼에서 remember 체크 시
String userId = req.getParameter("userId");
Cookie remember = new Cookie("rememberId",
URLEncoder.encode(userId, StandardCharsets.UTF_8));
remember.setPath("/"); // 필요한 최소 경로
remember.setMaxAge(60 * 60 * 24 * 30);// 30일
remember.setHttpOnly(true); // JS 접근 차단
remember.setSecure(true); // HTTPS에서만
resp.addCookie(remember);6-4. SameSite 설정(서블릿 표준 속성 미지원 시 헤더로)
// Some containers still need manual header for SameSite
String cookie = "rememberId=" + URLEncoder.encode(userId, StandardCharsets.UTF_8)
+ "; Max-Age=2592000; Path=/; HttpOnly; Secure; SameSite=Lax";
resp.setHeader("Set-Cookie", cookie);6-5. 쿠키 읽기
Cookie[] cookies = req.getCookies();
if (cookies != null) {
for (Cookie c : cookies) {
if ("rememberId".equals(c.getName())) {
String id = java.net.URLDecoder.decode(c.getValue(), StandardCharsets.UTF_8);
// 폼 기본값으로 채우기 등 활용
}
}
}| REST API 입문 가이드: 서버와 클라이언트가 데이터를 주고받는 기본 원리 (0) | 2026.06.09 |
|---|---|
| 📌"브라우저가 HTML을 어떻게 화면에 띄울까?" (1) | 2025.08.09 |
| 📌"브라우저가 URL을 입력하면 서버까지 무슨 일이 벌어질까 (3) | 2025.08.09 |
| 🧠 HTTP 상태코드 완전 정리하기 (재밌게, 쉽게, 한 방에!) (3) | 2025.08.04 |
| 🧩 RESTful API 제대로 알기: 개념부터 예제까지 한방에 정리! (2) | 2025.08.04 |