Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java - get cookie value by name in spring mvc

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?

like image 412
hamed Avatar asked Oct 14 '15 06:10

hamed


People also ask

How do I read cookies in spring boot controller?

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.

What is @CookieValue?

@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; }

What is the purpose of @CookieValue annotation in spring?

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.

Which annotation represents cookie values of requests?

Annotation which represents cookie values of requests. Explanation: Cookie values included in an incoming request, annotated with @CookieValue.


2 Answers

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"));
like image 53
meskobalazs Avatar answered Oct 10 '22 07:10

meskobalazs


You can also use org.springframework.web.util.WebUtils.getCookie(HttpServletRequest, String).

like image 14
ryanp Avatar answered Oct 10 '22 07:10

ryanp