In spring mvc 3, how to write a cookie while returning a ModelAndView?

前端 未结 4 629
心在旅途
心在旅途 2020-12-24 07:59

My controller method is returning a ModelAndView, but there is also a requirement to write a cookie back to client. Is it possible to do it in Spring? Thanks. <

4条回答
  •  猫巷女王i
    2020-12-24 08:26

    RustyX's solution in Java 8:

    @Component
        public class ModelCookieInterceptor extends HandlerInterceptorAdapter {
    
            @Override
            public void postHandle(HttpServletRequest req, HttpServletResponse res, Object handler, ModelAndView modelAndView) throws Exception{
                if (modelAndView != null) {
                    modelAndView.getModel().values().stream()
                        .filter(c -> c instanceof Cookie)
                        .map(c -> (Cookie) c)
                        .forEach(res::addCookie);
                }
            }
        }
    

提交回复
热议问题