// Cookie 생성은 범용적으로 사용될 수 있기 때문에 static 메서드로 선언
public static void addCookie(String cookieValue, HttpServletResponse res) {
try {
cookieValue = URLEncoder.encode(cookieValue, "utf-8").replaceAll("\\+", "%20"); // Cookie Value 에는 공백이 불가능해서 encoding 진행
Cookie cookie = new Cookie(AUTHORIZATION_HEADER, cookieValue); // Cookie에 저장될 Name과 Value를 생성자로 받는 Cookie 객체 생성
cookie.setPath("/"); // Path 지정
cookie.setMaxAge(30 * 60); // 만료시간 지정
// Response 객체에 Cookie 추가
// HttpServletResponse 객체에 생성한 Cookie 객체를 추가하여 브라우저로 반환
res.addCookie(cookie);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e.getMessage());
}
}
// @CookieValue("Cookie의 Name") : Cookie의 Name 정보를 전달해주면 해당 정보를 토대로 Cookie의 Value를 가져옴
@GetMapping("/get-cookie")
public String getCookie(@CookieValue(AUTHORIZATION_HEADER) String value) {
System.out.println("value = " + value);
return "getCookie : " + value;
}
위 그림에서와 같이 서버는 세션ID 를 사용하여 세션을 유지한다.
1. 클라이언트가 서버에 1번 요청
2. 서버가 세션ID 를 생성하고, 쿠키에 담아 응답 헤더에 전달
- 세션 ID 형태: "SESSIONID = 12A345"
3. 클라이언트가 쿠키에 세션ID를 저장 ('세션쿠키')
4. 클라이언트가 서버에 2번 요청
- 쿠키값 (세션 ID) 포함하여 요청
5. 서버가 세션ID 를 확인하고, 1번 요청과 같은 클라이언트임을 인지
Servlet에서는 유일무이한 '세션 ID'를 간편하게 만들수 있는 HttpSession을 제공 해줌
HttpSession 생성
@GetMapping("/create-session")
public String createSession(HttpServletRequest req) {
// 세션이 존재할 경우 세션 반환, 없을 경우 새로운 세션을 생성한 후 반환
HttpSession session = req.getSession(true);
// 세션에 저장될 정보 Name - Value 를 추가합니다.
session.setAttribute(AUTHORIZATION_HEADER, "Robbie Auth");
return "createSession";
}
반환된 세션은 브라우저 Cookie 저장소에 ‘JSESSIONID’라는 Name으로 Value에 저장됨
HttpSession 읽기
@GetMapping("/get-session")
public String getSession(HttpServletRequest req) {
// 세션이 존재할 경우 세션 반환, 없을 경우 null 반환
HttpSession session = req.getSession(false);
String value = (String) session.getAttribute(AUTHORIZATION_HEADER); // 가져온 세션에 저장된 Value 를 Name 을 사용하여 가져옵니다.
System.out.println("value = " + value);
return "getSession : " + value;
}
참고자료