쿠키는 서버에서 생성해서 클라이언트로 보낸다. 클라이언트는 받은 쿠키를 로컬 저장소(브라우저 내부 저장소)에 저장한다.
세션은 서버 측에서 생성, 저장되고 쿠키에 담아 브라우저와 주고받는다.
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); // Name-Value
cookie.setPath("/");
cookie.setMaxAge(30 * 60);
// Response 객체에 Cookie 추가
res.addCookie(cookie);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e.getMessage());
}
}
cookieValue = URLEncoder.encode(cookieValue, "utf-8").replaceAll("\\+", "%20");
쿠키 값의 Robbie Auth가 Robbie%20로 변환
- URLEncoder.encode(cookieValue, "utf-8") : 쿠키 값이 URL의 일부로 사용되기 때문에 URL로 인코딩해준다. URL 인코딩은 특수 문자를 % 기호와 함께 16진수로 변환하는데 공백은 +로 변환된다.
- replaceAll("\\+", "%20") : + 문자를 %20으로 변환한다.
즉 위 코드는 cookieValue에 포함된 공백을 %20으로 변환해서 쿠키 value의 공백을 없앤다.
@GetMapping("/get-cookie")
public String getCookie(@CookieValue(AUTHORIZATION_HEADER) String value) {
System.out.println("value = " + value);
return "getCookie : " + value;
}
@CookieValue(추출할 쿠키의 네임) : HTTP 요청에서 특정 쿠키를 추출해 메서드 매개변수로 주입한다.