In spring mvc 3, how to write a cookie while returning a ModelAndView?
Not as part of the ModelAndView
, no, but you can add the cookie directly to the HttpServletResponse
object that's passed in to your controller method.
If you add the response as parameter to your handler method (see flexible signatures of @RequestMapping
annotated methods – same section for 3.2.x, 4.0.x, 4.1.x, 4.3.x, 5.x.x), you may add the cookie to the response directly:
Kotlin
@RequestMapping(["/example"])
fun exampleHandler(response: HttpServletResponse): ModelAndView {
response.addCookie(Cookie("COOKIENAME", "The cookie's value"))
return ModelAndView("viewname")
}
Java
@RequestMapping("/example")
private ModelAndView exampleHandler(HttpServletResponse response) {
response.addCookie(new Cookie("COOKIENAME", "The cookie's value"));
return new ModelAndView("viewname");
}