[ACCEPTED]-In spring mvc 3, how to write a cookie while returning a ModelAndView?-cookies
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:
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");
}
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.
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
.
@Component
public class ModelCookieInterceptor extends HandlerInterceptorAdapter {
@Override
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
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.