3

我正在尝试将 Spring MVC 配置为具有以下方案:

  • 任何以“{context}/resources”开头的 url 都应该是可缓存的
  • 任何其他 url 都不应该是可缓存的(在我的情况下,“资源”的所有内容都是动态页面)

第一部分很容易使用 mvc:resource :

<mvc:resources mapping="/resources/**" location="..." cache-period="3600"/>

我有点迷失了第二部分。默认情况下,“动态资源”似乎没有与缓存相关的信息(没有缓存控制标头、没有编译指示等)。有些浏览器可能会缓存东西(FF),有些可能不会(Chrome),这是可以理解的。

有很多关于如何使用 WebContentInterceptor 和 WebContentInterceptor 的组合来使某些页面可缓存的帖子:

<mvc:interceptors>
    <mvc:interceptor>
        <mvc:mapping path="/foobar/**"/>
        <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:interceptor>
</mvc:interceptors>

但是,在我的情况下,这是不可用的,因为我没有要匹配的路径表达式(众所周知,排除是不可能的)。

那么有没有一种方法可以表达这一点: * 做 mvc:resources 为资源做的事情 * 为所有其他页面做“某事”?

我能看到的唯一选择是编写一个自定义拦截器,它会检查某个东西是否是资源,但这听起来有点奇怪,不能全局定义缓存属性。

谢谢

4

1 回答 1

1

Spring MVC 的行为正是您想要的方式。WebContentInterceptor仅拦截文本/html资源请求并将缓存控制添加到请求中。

对所有 url 执行此操作的方法是将<mvc:mapping>排除在配置之外:

<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:interceptor>

此外,由于<mvc:interceptors><mvc:resources>是独立的,因此这两个标签的任何特定顺序都不重要(与此处答案中的建议不同)。

于 2013-06-21T12:38:11.910 回答