How do you set cache headers in Spring MVC?

后端 未结 10 1081
名媛妹妹
名媛妹妹 2020-12-04 09:23

In an annotation-based Spring MVC controller, what is the preferred way to set cache headers for a specific path?

10条回答
  •  北荒
    北荒 (楼主)
    2020-12-04 09:48

    I just encountered the same problem, and found a good solution already provided by the framework. The org.springframework.web.servlet.mvc.WebContentInterceptor class allows you to define default caching behaviour, plus path-specific overrides (with the same path-matcher behaviour used elsewhere). The steps for me were:

    1. Ensure my instance of org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter does not have the "cacheSeconds" property set.
    2. Add an instance of WebContentInterceptor:

      
      ...
      
          
              
                  
                  2592000
                  
                  -1
              
          
      
      ...
      
      

    After these changes, responses under /foo included headers to discourage caching, responses under /cache/me included headers to encourage caching, and responses under /cache/agnostic included no cache-related headers.


    If using a pure Java configuration:

    @EnableWebMvc
    @Configuration
    public class WebMvcConfig extends WebMvcConfigurerAdapter {
      /* Time, in seconds, to have the browser cache static resources (one week). */
      private static final int BROWSER_CACHE_CONTROL = 604800;
    
      @Override
      public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry
         .addResourceHandler("/images/**")
         .addResourceLocations("/images/")
         .setCachePeriod(BROWSER_CACHE_CONTROL);
      }
    }
    

    See also: http://docs.spring.io/spring-security/site/docs/current/reference/html/headers.html

提交回复
热议问题