Tomcat is setting no-cache for JS and CSS file

bobber205 picture bobber205 · Apr 22, 2011 · Viewed 17.4k times · Source

So frustrating. :P

Really would like these to be cached on users' browsers but it's setting this.

Cache-Control:no-store, no-cache, must-revalidate, post-check=0, pre-check=0

How do I stop this?

I've tried looking in our settings for anything relating to caching. All default values are used which according to the documentation, that means it's allowed. Are static files like JS and CSS different?

Edit: I've noticed that some JS files are being allowed to cache as Chrome is saying they were "retrieved from cache". No CSS files are however.

Answer

rekaszeru picture rekaszeru · Apr 22, 2011

You could write your own cache filter, and configure it in your web xml.

Here you find a basic, yet great example of how to implement it.

in your web.xml you declare your filter:

<filter>
    <description>Set HTTP headers for a mapping.</description>
    <filter-name>CacheFilter</filter-name>
    <filter-class>your.package.CacheFilter</filter-class>
    <init-param>
        <description>Adds an expires header to the response</description>
        <param-name>header</param-name>
        <param-value>Expires: Thu, 26 Apr 2012 20:00:00 GMT</param-value>
    </init-param>
</filter>

then map it (apply it to responses):

<filter-mapping>
    <filter-name>CacheFilter</filter-name>
    <url-pattern>*.js</url-pattern>
    <dispatcher>REQUEST</dispatcher>
</filter-mapping>
<filter-mapping>
    <filter-name>CacheFilter</filter-name>
    <url-pattern>*.css</url-pattern>
    <dispatcher>REQUEST</dispatcher>
</filter-mapping>

You might also want to use a compress filter (this same way), to reduce the load of data sent from the server. This implementation of a gzip filter works for me for years now (along the cache filter), and never had any problem with them.