[ACCEPTED]-In spring mvc 3, how to write a cookie while returning a ModelAndView?-cookies

Accepted answer
Score: 54

If you add the response as parameter to 3 your handler method (see flexible signatures of @RequestMapping annotated methods – same section 2 for 3.2.x, 4.0.x, 4.1.x, 4.3.x, 5.x.x), you may add the cookie to the response 1 directly:


fun exampleHandler(response: HttpServletResponse): ModelAndView {
   response.addCookie(Cookie("COOKIENAME", "The cookie's value"))
   return ModelAndView("viewname")


private ModelAndView exampleHandler(HttpServletResponse response) {

        response.addCookie(new Cookie("COOKIENAME", "The cookie's value"));

        return new ModelAndView("viewname");
Score: 10

Not as part of the ModelAndView, no, but you can add the cookie directly to 2 the HttpServletResponse object that's passed in to your controller 1 method.

Score: 8

You can write a HandlerInterceptor that will take all Cookie 6 instances from your model and generate the 5 appropriate cookie headers. This way you 4 can keep your controllers clean and free 3 from HttpServletResponse.

public class ModelCookieInterceptor extends HandlerInterceptorAdapter {

    public void postHandle(HttpServletRequest req, HttpServletResponse res, Object handler, ModelAndView modelAndView) throws Exception {
        if (modelAndView != null) {
            for (Object value : modelAndView.getModel().values()) {
                if (value instanceof Cookie)
                    res.addCookie((Cookie) value);


NB . Don't forget to register the 2 interceptor either with <mvc:interceptors> (XML config) or 1 WebMvcConfigurer.addInterceptors() (Java config).

More Related questions