Abdus Samad
Abdus Samad

Reputation: 351

Spring WebContentInterceptor is not adding cacheSeconds to header

I am trying to add configuration in spring mvc so that my static contents like js, images will be cached by browser. I have add the following in dispatcher-servlet.xml

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

But i still dont see the caching is enabled. I see the following in the browser debugger where it says Cache-Control:"no-cache".

Firefox Debugger

Please help !!!

Upvotes: 4

Views: 3883

Answers (3)

Almer
Almer

Reputation: 1199

I had the same problem. I added the interceptor but noting changed in the HTTP reponses.

In my case there was another spring context XML in my project where another <mvc:interceptors> was registered. It effectivly replaced my WebContentInterceptor configuration. Combining them solved it.

Perhaps something similar is going on in your configuration Abdus Samad...

Upvotes: 0

Brian Clozel
Brian Clozel

Reputation: 59211

You're missing the cacheMappings property to configure path patterns / cache directives.

<bean id="webContentInterceptor" class="org.springframework.web.servlet.mvc.WebContentInterceptor">
  <property name="cacheSeconds" value="31556926"/>
  <property name="useExpiresHeader" value="true"/>
  <property name="useCacheControlHeader" value="true"/>
  <property name="useCacheControlNoStore" value="true"/>
  <property name="cacheMappings">
    <props>
      <prop key="/static/**">2592000</prop>
    </props>
  </property>
</bean>

But indeed, Burak Keceli's answer is spot on; you'd better use WebMvcConfigurerAdapter.addResourceHandlers or the XML configuration version with <mvc:resources/>.

Upvotes: 0

Burak Keceli
Burak Keceli

Reputation: 953

You can use mvc:resources for caching static files.

<mvc:resources mapping="/static/**" location="/public-resources/" 
       cache-period="31556926"/>
<mvc:annotation-driven/>

Upvotes: 1

Related Questions