Java Spring 환경에서 웹 쿠키를 생성하고 클라이언트와 주고받는 방법을 잊지 않기 위해 기록한다.
@RestController
public class AuthController {
public String AUTHORIZATION_HEADER = "Authorization";
@GetMapping("/create-cookie")
public String createCookie(HttpServletResponse res) {
String cookieValue = "User Auth";
try {
cookieValue = URLEncoder.encode(cookieValue, "utf-8").replaceAll("\\+", "%20");
// 쿠키 생성
Cookie cookie = new Cookie(AUTHORIZATION_HEADER, cookieValue);
cookie.setPath("/");
cookie.setMaxAge(30 * 60);
// 쿠키 세팅
res.addCookie(cookie);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e.getMessage());
}
return "Create cookie";
}
...
}
@RestController
public class AuthController {
public String AUTHORIZATION_HEADER = "Authorization";
...
@GetMapping("/get-cookie")
public String getCookie(HttpServletRequest req) {
Cookie[] cookies = req.getCookies();
if(cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals(AUTHORIZATION_HEADER)) {
try {
return "Get Cookie: " + URLDecoder.decode(cookie.getValue(), "UTF-8");
} catch (UnsupportedEncodingException e) {
return "Fail";
}
}
}
return "Cannot find auth Cookie";
}
return "No exist Cookies";
}
}
@RestController
public class AuthController {
public String AUTHORIZATION_HEADER = "Authorization";
...
@GetMapping("/get-cookie")
public String getCookie(@CookieValue(AUTHORIZATION_HEADER) String value) {
return "Get Cookie: " + value;
}
}