一尘不染

如何在Spring MVC中设置缓存头?

spring

如何在Spring MVC中设置缓存头?


阅读 354

收藏
2020-04-19

共2个答案

一尘不染

/* 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);

它们可以在内容生成之前在控制器中调用,也可以在Spring上下文中指定为bean属性。

2020-04-19
一尘不染

我只是遇到了同样的问题,并且发现框架已经提供了一个很好的解决方案。该org.springframework.web.servlet.mvc.WebContentInterceptor级允许你定义默认缓存行为,加上路径特定的覆盖(具有相同的路径匹配行为别处使用)。对我来说,步骤是:

  1. 确保我的实例org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter未设置“ cacheSeconds”属性。
  2. 添加一个实例WebContentInterceptor
<mvc:interceptors>
...
<bean class="org.springframework.web.servlet.mvc.WebContentInterceptor" p:cacheSeconds="0" p:alwaysUseFullPath="true" >
    <property name="cacheMappings">
        <props>
            <!-- cache for one month -->
            <prop key="/cache/me/**">2592000</prop>
            <!-- don't set cache headers -->
            <prop key="/cache/agnostic/**">-1</prop>
        </props>
    </property>
</bean>
...
</mvc:interceptors>

在进行这些更改之后,/ foo下的响应包括不鼓励缓存的头,/ cache / me下的响应包括鼓励缓存的头,/ cache / agnostic下的响应不包括与缓存相关的头。

如果使用纯Java配置:

@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);
  }
}
2020-04-19