I'm working on a java spring mvc application. I have set a cookie in one of my controller's methods in this way:
@RequestMapping(value = {"/news"}, method = RequestMethod.GET)
public ModelAndView news(Locale locale, Model model, HttpServletResponse response, HttpServletRequest request) throws Exception {
...
response.setHeader("Set-Cookie", "test=value; Path=/");
...
modelAndView.setViewName("path/to/my/view");
return modelAndView;
}
This is working fine and I can see a cookie with name test
and value "value" in my browser console. Now I want to get the cookie value by name in other method. How can I get value of test
cookie?
To read all cookies, you can use HttpServletRequest 's getCookies() method which returns an array of Cookie . Max-Age directive specifies the date and time when the cookie should expire. If you are storing sensitive information in a cookie, make sure to set Secure and HttpOnly flags to avoid XSS attacks.
@CookieValue is used in a controller method and maps the value of a cookie to a method parameter: @GetMapping("/read-spring-cookie") public String readCookie( @CookieValue(name = "user-id", defaultValue = "default-user-id") String userId) { return userId; }
Annotation Type CookieValue Annotation to indicate that a method parameter is bound to an HTTP cookie. The method parameter may be declared as type Cookie or as cookie value type (String, int, etc.). Note that with spring-webmvc 5.3. x and earlier, the cookie value is URL decoded.
Annotation which represents cookie values of requests. Explanation: Cookie values included in an incoming request, annotated with @CookieValue.
The simplest way is using it in a controller with the @CookieValue
annotation:
@RequestMapping("/hello")
public String hello(@CookieValue("foo") String fooCookie) {
// ...
}
Otherwise, you can get it from the servlet request using Spring org.springframework.web.util.WebUtils
WebUtils.getCookie(HttpServletRequest request, String cookieName)
By the way, the code pasted into the question could be refined a bit. Instead of using #setHeader()
, this is much more elegant:
response.addCookie(new Cookie("test", "value"));
You can also use org.springframework.web.util.WebUtils.getCookie(HttpServletRequest, String)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With