How do you set cache headers in Spring MVC?

后端 未结 10 1049
名媛妹妹
名媛妹妹 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:51

    In your controller, you can set response headers directly.

    response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
    response.setHeader("Pragma", "no-cache");
    response.setDateHeader("Expires", 0);
    
    0 讨论(0)
  • 2020-12-04 09:53

    I found WebContentInterceptor to be the easiest way to go.

    @Override
    public void addInterceptors(InterceptorRegistry registry)
    {
        WebContentInterceptor interceptor = new WebContentInterceptor();
        interceptor.addCacheMapping(CacheControl.noCache(), "/users", "admin");
        registry.addInterceptor(interceptor);
    }
    
    0 讨论(0)
  • 2020-12-04 09:58

    org.springframework.web.servlet.support.WebContentGenerator, which is the base class for all Spring controllers has quite a few methods dealing with cache headers:

    /* Set whether to use the HTTP 1.1 cache-control header. Default is "true".
     * <p>Note: Cache headers will only get applied if caching is enabled
     * (or explicitly prevented) for the current request. */
    public final void setUseCacheControlHeader();
    
    /* Return whether the HTTP 1.1 cache-control header is used. */
    public final boolean isUseCacheControlHeader();
    
    /* Set whether to use the HTTP 1.1 cache-control header value "no-store"
     * when preventing caching. Default is "true". */
    public final void setUseCacheControlNoStore(boolean useCacheControlNoStore);
    
    /* Cache content for the given number of seconds. Default is -1,
     * indicating no generation of cache-related headers.
     * Only if this is set to 0 (no cache) or a positive value (cache for
     * this many seconds) will this class generate cache headers.
     * The headers can be overwritten by subclasses, before content is generated. */
    public final void setCacheSeconds(int seconds);
    

    They can either be invoked within your controller prior to content generation or specified as bean properties in Spring context.

    0 讨论(0)
  • 2020-12-04 09:59

    You could extend AnnotationMethodHandlerAdapter to look for a custom cache control annotation and set the http headers accordingly.

    0 讨论(0)
提交回复
热议问题