2011-02-03 27 views

Trả lời

46

Nếu bạn thêm các phản ứng như tham số để phương pháp xử lý của bạn (xem flexible signatures of @RequestMapping annotated methods - cùng phần cho 3.2.x, 4.0.x, 4.1.x, 4.3.x, 5.0.x), bạn có thể add the cookie để phản ứng trực tiếp:

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"); 
} 
+0

Đôi khi bạn cần phải gọi 'cookie.setPath ("xxx"); 'nếu bạn muốn chia sẻ các tập tin cookie giữa các yêu cầu. –

10

Không phải là một phần của ModelAndView, không, nhưng bạn có thể add the cookie directly đối tượng HttpServletResponse được chuyển vào phương pháp điều khiển của bạn.

5

Bạn có thể viết HandlerInterceptor sẽ lấy tất cả các phiên bản Cookie từ mô hình của bạn và tạo ra các tiêu đề cookie thích hợp. Bằng cách này bạn có thể giữ cho bộ điều khiển của bạn sạch sẽ và miễn phí từ 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. Đừng quên đăng ký máy đánh chặn với <mvc:interceptors> (cấu hình XML) hoặc WebMvcConfigurer.addInterceptors() (cấu hình Java).

+0

Điều này đặc biệt hữu ích nếu bạn muốn định cấu hình có trả lại dữ liệu dưới dạng Cookie, Tiêu đề, JSON, v.v. và cung cấp sự phân tách mối quan tâm tốt. – kuporific

+0

Đây là mã mẫu thực sự tốt. – mahesh

0

giải pháp RustyX trong 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); 
      } 
     } 
    } 
Các vấn đề liên quan