导致这种情况的根代码在 Spring MVC 中,从 WebContentGenerator 调用。该类用作 MVC/Webflow 堆栈中几个类的基类:WebContentInterceptor(MVC 拦截器)、AbstractController(MVC 控制器)、AbstractHandlerMethodAdapter(MVC HandlerAdapter)、AnnotationMethodHadlerAdapter(MVC HandlerAdapter)、FlowHandlerAdapter(Webflow HandlerAdapter)、JsfFlowHandlerAdapter(Webflow + JSF 处理适配器)
CacheControl 秒设置为 0 调用 preventCaching 方法。因此,应用程序似乎默认设置为 0。
org.springframework.web.servlet.support.WebContentGenerator
protected final void preventCaching(HttpServletResponse response) {
response.setHeader(HEADER_PRAGMA, "no-cache");
if (this.useExpiresHeader) {
// HTTP 1.0 header
response.setDateHeader(HEADER_EXPIRES, 1L);
}
if (this.useCacheControlHeader) {
// HTTP 1.1 header: "no-cache" is the standard value,
// "no-store" is necessary to prevent caching on FireFox.
response.setHeader(HEADER_CACHE_CONTROL, "no-cache");
if (this.useCacheControlNoStore) {
response.addHeader(HEADER_CACHE_CONTROL, "no-store");
}
}
}
我发现由于我使用的是 JSF + Webflow,因此 JsfFlowHandlerAdapter 首先处理服务器对流/视图的请求。这就是为什么配置拦截器没有帮助的原因,因为此时 JsfFlowHandlerAdapter 已经设置了 Cache-Control 和其他 HTTP 标头。事实证明,我已经扩展了 JsfFlowHandlerAdapter 以处理 FlowExecutionRestorationFailureException(请参阅Sping Web Flow 防止返回按钮使用),所以我需要做的就是设置我想要的配置(因为配置属于基类 WebContentGenerator)。
自定义 JsfFlowHandlerAdapter
public class MyAppFlowHandlerAdapter extends org.springframework.faces.webflow.JsfFlowHandlerAdapter {
...
}
webmvc-config.xml
<!-- Dispatches requests mapped to flows to FlowHandler implementations -->
<bean
class="com.myapp.MyAppFlowHandlerAdapter">
<property name="flowExecutor" ref="flowExecutor" />
<!-- Disable built in Cache-Control settings -->
<property name="cacheSeconds" value="-1" />
<property name="useExpiresHeader" value="false" />
<property name="useCacheControlHeader" value="false" />
<property name="useCacheControlNoStore" value="false" />
</bean>
<!-- Maps request paths to flows in the flowRegistry; e.g. a path of /hotels/booking
looks for a flow with id "hotels/booking" -->
<bean class="org.springframework.webflow.mvc.servlet.FlowHandlerMapping">
<!-- snip out unimportant -->
<property name="interceptors">
<list>
<ref bean="cacheControlInterceptor" />
</list>
</property>
</bean>
<bean id="cacheControlInterceptor"
class="com.myapp.CacheControlInterceptor">
CacheControlInterceptor(设置您自己的 HTTP 标头。在 WebContentGenerator 中执行此操作的方法是最终的,因此不能 @Override)
public class CacheControlInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//Example below: set your Cache-Control, expires, pragma headers here
response.setHeader("Cache-Control", "private");
return true;
}
}