Spring-Framework (Spring-boot) 쿠키 생성 및 제거

Aaaalpooo
3 min readOct 23, 2018

쿠키 생성

@RequestMapping(value="/some/path", method = RequestMethod.POST)public void ResponseEntity<?> someMethod(HttpServletResponse response) {   Cookie myCookie = new Cookie("cookieName", cookieValue);
myCookie.setMaxAge(쿠키 expiration 타임 (int));
myCookie.setPath("/"); // 모든 경로에서 접근 가능 하도록 설정
response.addCookie(myCookie);
}

쿠키 제거

@RequestMapping(value="/some/path", method = RequestMethod.POST)public void ResponseEntity<?> someMethod(HttpServletResponse response) {    //원래 쿠키의 이름이 userInfo 이었다면, value를 null로 처리.    Cookie myCookie = new Cookie("userInfo", null);
myCookie.setMaxAge(0); // 쿠키의 expiration 타임을 0으로 하여 없앤다.
myCookie.setPath("/"); // 모든 경로에서 삭제 됬음을 알린다.
response.addCookie(myCookie);
}

모든 쿠키 가져오기 및 특정 쿠키 정보 추출

@RequestMapping(value="/some/path", method = RequestMethod.POST)public void ResponseEntity<?> someMethod(HttpServletRequest request) {    Cookie[] myCookies = request.getCookies();
for(int i = 0; i < myCookies.length; i++) {
System.out.println(i + "번째 쿠키 이름: " + myCookies[i].getName());
System.out.println(i + "번째 쿠키 값: " + myCookies[i].getValue());
}}

정리

쿠키를 가져올땐 HttpServletRequest 에서 가져오고,

쿠키를 설정할땐 HttpServletResponse로 설정한다.

--

--