A common practice was to getCookies from HttpServletRequest and retrieve from it. It looks like this:
CookieController.java
@GetMapping("cookies3")
public String showCookies3(HttpServletRequest httpServletRequest) {
Cookie[] cookies = httpServletRequest.getCookies();
Arrays.stream(cookies).forEach(cookie -> System.out.println(cookie.getValue()));
return VIEW_NAME;
}
However, you can get it a little easier by using Spring.
Set the cookie appropriately.
CookieController.java
private final String VIEW_NAME = "demo/cookie/index";
@GetMapping("/")
public String index(HttpServletResponse httpServletResponse) {
httpServletResponse.addCookie(new Cookie("key1", "value1"));
return VIEW_NAME;
}
It can be easily obtained by using the CookieValue annotation as shown below. The argument is the cookie key value.
CookieController.java
private final String VIEW_NAME = "demo/cookie/index";
@GetMapping("cookies1")
public String showCookies1(@CookieValue("key1") String cookieValue) {
System.out.println(cookieValue);
return VIEW_NAME;
}
However, if the above writing method is used and the cookie cannot be obtained due to deletion, a runtime error will occur. ※Resolved [org.springframework.web.bind.MissingRequestCookieException: Missing cookie 'key1' for method parameter of type String])
Therefore, it can be avoided by setting required of @CookieValue to false (default is required = true) as shown below.
However, in this case, null is set in the argument, so by specifying the defaultValue attribute, it is possible to specify the default value if it cannot be obtained from the cookie.
CookieController.java
private final String VIEW_NAME = "demo/cookie/index";
@GetMapping("cookies2")
public String showCookies2(
@CookieValue(name = "key1", required = false, defaultValue = "default value1") String cookieValue) {
System.out.println(cookieValue);
return VIEW_NAME;
}
that's all.
Recommended Posts