Setting and reading cookie in Spring MVC

Posted on 29-04-2013 14:27 by graham
Spring MVC gives you methods with which you can create cookie and read them from within a controller method.

Creating a cookie

To set a cookie from within a controller action method in Spring MVC, you need to call the addCookie method on the response object.
private ModelAndView setCookie(HttpServletResponse response)
response.addCookie(new Cookie("COOKIE_NAME", "Cookie value"));
return new ModelAndView("someview");

Note the HttpServletResponse response parameter added to the action method.

Reading a cookie

To read a cookie, use the @CookieValue annotation on a controller action's parameter:
private ModelAndView setCookie(@CookieValue("COOKIE_NAME") String cookie)
// the cookie parameter contains the value of the cookie
For setting a cookie, do you have to return a model and view, or can the method be void?
Added on 18-11-2013 22:30 by anonymous


Add comment

Has this tutorial been helpful to you? Or do you see anything wrong? We appreciate your opinion!
Your comment:
Show formatting hints
HTML is disallowed, but in your text you can use the following markup
  • [code][/code] for a block of code
  • [tt][/tt] for inline code
  • [link]link href|link anchor[/link] for links
  • [b][/b] for bold text
+ Ask a question
If you have a technical question related to programming and computers, ask it here. Other users will help you solve it!
Unanswered questions
Share your knowledge by helping others solve their problems