스프링에서 cookie 생성,사용 session생성,사용 하는 방법을 배워 보았다.
자세한 설명은 주석 참조
@RestController
@RequestMapping("/api")
public class AuthController {
public static final String AUTHORIZATION_HEADER = "Authorization";
@GetMapping("/create-cookie")
public String createCookie(HttpServletResponse res) {
addCookie("Robbie Auth", res); // 쿠키 생성하기
return "createCookie";
}
@GetMapping("/get-cookie")
public String getCookie(@CookieValue(AUTHORIZATION_HEADER) String value) { //쿠키 값을 가져오는 방법 @CookieValue(쿠키이름)
System.out.println("value = " + value);
return "getCookie : " + value;
}
@GetMapping("/create-session")
public String createSession(HttpServletRequest req) { //http 요청 받아온다
// 세션이 존재할 경우 세션 반환, 없을 경우 새로운 세션을 생성한 후 반환
HttpSession session = req.getSession(true);
// 세션에 저장될 정보 Name - Value 를 추가합니다.
session.setAttribute(AUTHORIZATION_HEADER, "Robbie Auth");
return "createSession";
}
@GetMapping("/get-session")
public String getSession(HttpServletRequest req) {
// 세션이 존재할 경우 세션 반환, 없을 경우 null 반환
HttpSession session = req.getSession(false);
// 가져온 세션에 저장된 Value 를 Name 을 사용하여 가져옵니다.(Object로 반환하기 때문에 String 으로 캐스팅 해줌)
String value = (String) session.getAttribute(AUTHORIZATION_HEADER);
System.out.println("value = " + value);
return "getSession : " + value;
}
// 쿠키 생성하기
public static void addCookie(String cookieValue, HttpServletResponse res) {
try {
// Cookie Value 에는 공백이 불가능해서 encoding 진행
// URLEncoder.encode(cookieValue, "utf-8") → 매개변수 1 : 인코딩할 value 매개변수2 : 인코딩 방식
// replaceAll("\\+", "%20") → 매개변수1:정규표현식(변경할부분), 매개변수2 : 변경할 내용 / "\\+" 뜻 : 공백!
cookieValue = URLEncoder.encode(cookieValue, "utf-8").replaceAll("\\+", "%20");
// 스프링에서 제공하는 Cookie 클래스
Cookie cookie = new Cookie(AUTHORIZATION_HEADER, cookieValue); // Name-Value 형식
cookie.setPath("/"); // path
cookie.setMaxAge(30 * 60); // 만료기한
// Response 객체에 Cookie 추가
res.addCookie(cookie);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e.getMessage());
}
}
}