Skip to content
Samuel Santos edited this page Oct 23, 2013 · 6 revisions

CacheFilter is a Java Servlet filter that allows you to enable browser caching for requested resources.

Filter parameters

Option Required Default Description
static No false Defines whether a component is a static asset or not. Conditional requests(1) are not required for static components.
private No false Cache directive to control where the response may be cached.
  • false indicates that the response MAY be cached by any cache.
  • true indicates that the response is intended for a single user and MUST NOT be cached by a shared cache, a private (non-shared) cache MAY cache the response.
expirationTime Yes -- Cache directive to set an expiration time, in seconds, relative to the current date.

(1) If a component is already in the browser's cache and is being re-requested, the browser will pass the Last-Modified date in the request header. This is called a conditional GET request and if the component has not been modified, the server will return a 304 Not Modified response.

Sample configuration

Declare the filter in your web descriptor file web.xml:

<filter>
    <filter-name>imagesCache</filter-name>
    <filter-class>com.samaxes.filter.CacheFilter</filter-class>
    <init-param>
        <param-name>static</param-name>
        <param-value>true</param-value>
    </init-param>
    <init-param>
        <param-name>expirationTime</param-name>
        <param-value>2592000</param-value>
    </init-param>
</filter>

<filter>
    <filter-name>cssCache</filter-name>
    <filter-class>com.samaxes.filter.CacheFilter</filter-class>
    <init-param>
        <param-name>expirationTime</param-name>
        <param-value>604800</param-value>
    </init-param>
</filter>

<filter>
    <filter-name>jsCache</filter-name>
    <filter-class>com.samaxes.filter.CacheFilter</filter-class>
    <init-param>
        <param-name>private</param-name>
        <param-value>true</param-value>
    </init-param>
    <init-param>
        <param-name>expirationTime</param-name>
        <param-value>216000</param-value>
    </init-param>
</filter>

Map the filter to serve your static resources:

<filter-mapping>
    <filter-name>imagesCache</filter-name>
    <url-pattern>/img/*</url-pattern>
</filter-mapping>

<filter-mapping>
    <filter-name>cssCache</filter-name>
    <url-pattern>*.css</url-pattern>
</filter-mapping>

<filter-mapping>
    <filter-name>jsCache</filter-name>
    <url-pattern>*.js</url-pattern>
</filter-mapping>

Clone this wiki locally