Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enable HTTP caching for the resource handler with Spring MVC and Spring Security

I wish to enable HTTP caching for some static resources such as images, for which access is restricted by Spring Security. (These resources are not security critical, but shouldn't be publicly accessible either). How do I avoid having Spring Security add HTTP response headers that disable caching?

If I add setCachePeriod() into my resource handler registration in WebMvcConfigurerAdapter.addResourceHandlers() as following:

registry.addResourceHandler("/static/**")
  .addResourceLocations("classpath:/static/").setCachePeriod(3600);

The resources are still returned with following headers that disable caching:

Cache-Control: max-age=3600, must-revalidate
Expires: Mon, 04 Aug 2014 07:45:36 GMT
Pragma: no-cache

I want to avoid introducing any XML configuration into the project, which currently uses only Java annotation configuration.

Are there better solutions than extending the Spring resource handler?

like image 493
Samuli Pahaoja Avatar asked Aug 04 '14 06:08

Samuli Pahaoja


1 Answers

You can use webContentInterceptor resource to allow static resource caching.

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

Using annotations to configure cache interceptors is done following way. In your web config class you can add a bean for WebContentInterceptor class and add it into interceptors list.

@Bean
public WebContentInterceptor webContentInterceptor() {
    WebContentInterceptor interceptor = new WebContentInterceptor();
    interceptor.setCacheSeconds(31556926);
    interceptor.setUseExpiresHeader(true);;
    interceptor.setUseCacheControlHeader(true);
    interceptor.setUseCacheControlNoStore(true);
    return interceptor;
}

@Override
public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(webContentInterceptor());
}

Refer this site to see how it's done.

like image 155
Jeevan Patil Avatar answered Sep 26 '22 02:09

Jeevan Patil