java - 如何在 Spring 4.2 或更高版本中设置 Cache-control : private with applicationContext. xml

标签 java xml spring spring-mvc caching

如何在 Spring 4.2 或更高版本中使用 applicationContext.xml 设置 Cache-control: private?

背景:

Cache-control: HTTP header 可以在 Spring 4.1 中从 applicationContext.xml 设置,如下所示:

<mvc:interceptors>
  <bean id="webContentInterceptor"
        class="org.springframework.web.servlet.mvc.WebContentInterceptor">
    <property name="cacheSeconds" value="0"/>
    <property name="useExpiresHeader" value="true"/>
    <property name="useCacheControlHeader" value="true"/>
    <property name="useCacheControlNoStore" value="true"/>
  </bean>
</mvc:interceptors>

有一些基于注释的实现,例如 https://github.com/foo4u/spring-mvc-cache-control ,但我更喜欢基于 XML 的配置,因为我必须根据测试/生产环境更改 HTTP header (例如,如果页面返回 Cache-Control: private, no-store, Chrome 会发送另一个“查看页面源代码”请求,无缓存、必须重新验证,并使反 CSRF token 不匹配)。

问题:

从 Spring 4.2 开始,这些设置已被弃用。 此外,无法从这些设置中设置Cache-control: private。由于某些 CDN 提供商当且仅当 http header 包含 Cache-Control: private 时才存储内容,因此对此 HTTP header 的支持对于使用 CDN 的系统至关重要。例如http://tech.mercari.com/entry/2017/06/22/204500https://community.fastly.com/t/fastly-ttl/882 .

因此,为了安全起见,我正在寻找从 applicationContext.xml 设置 Cache-Control: private HTTP header 的方法。

最佳答案

Spring 4.2+ 中似乎没有现成的 XML 支持。如您所见hereWebContentInterceptorcacheControlMappings没有set方法,因此没有机会将XML配置中的值写入其中;该映射旨在存储 url-cache-control 映射。然而,CacheControl类具有公共(public) cachePrivate 方法,可用于注册自定义配置(我认为这可以针对 dev 或 prod 配置文件完成);例如:

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    CacheControl cacheControl = CacheControl.empty().cachePrivate();
    registry.addResourceHandler("/**")
                .setCacheControl(cacheControl);
}

或者直接在您的 Controller 中(也可能取决于 Activity 配置文件):

@RequestMapping(value = "/test")
public ResponseEntity<?> doHandleRequest () {
    CacheControl cacheControl = CacheControl.empty().cachePrivate();
    return ResponseEntity.ok()
                         .cacheControl(cacheControl);
}

如果您确实需要使用 XML 配置,没有人会阻止您使用适当的方法和逻辑编写 WebContentInterceptor 的自定义子类,幸运的是,WebContentInterceptoraddCacheMapping 方法。

关于java - 如何在 Spring 4.2 或更高版本中设置 Cache-control : private with applicationContext. xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46159288/

相关文章:

Java Spring Controller 处理一个荒谬的 url

java - 启动 Sonar 服务 - java.lang.OutOfMemoryError : GC overhead limit exceeded Ubuntu

java - 在 Web 收获 xml 中使用正则表达式

java - 如何在 Spring Integration 中的异常路由器中使用根本原因异常类型

java - 无法发布到服务器。无法获取 J2EEFlexProjDeployable 对象

java - Android 谷歌地图不显示我的位置?

c# - 如何将枚举序列化为 XML 文本

java - gdata 到 java 对象的映射

spring - 如何在独立的 Turbine 应用程序中激活/turbine.stream 端点

java - 我如何在 Spring 中使用角色?