OSCache - CacheFilter Tutorial

### Introduction OSCache comes with a servlet filter that enables you to transparently cache entire pages of your website, and even binary files. Caching of binary files is extremely useful when they are generated dynamically, e.g. PDF files or images. In addition by using the last modified header the transaction overhead and server load is reduced excellently which speed ups the server response time. How to configure OSCache to cache entire servlet responses is described in the configuration page of the CacheFilter. This short tutorial should demonstrate how to make your web site more responsive, and save load on your server. Using the CacheFilter the user will appreciate a faster loading site and will visit it more often. ### Improvements Major improvements have been made to the CacheFilter in the releases 2.2 and 2.3: Default initialization of the last modified header which reduces transaction overhead and server load CRON expressions to expire content at specific dates and/or times Preserving more http headers, e.g. the expires header Special handling for fragments of a page Custom cache key generation by subclassing CacheFilter or by implementing a special interface Custom cache groups generation by subclassing CacheFilter or by implementing a special interface Support of GZip filters in the filter chain Avoids session creation for application scope pages Reduced memory consumption Multiple matching cache filters won't dead-lock the response anymore The cache won't be serve the same response twice before the client begins to cache it anymore ### Cacheable Content
| Cacheable content Note that the filter will only cache content that has a status of 200 (HttpServletResponse.SC_OK).
### Configuring the filter #### Example 1 To configure the filter, add something like the following to your `web.xml` file (obviously you will want to set the URL pattern to match only the content you want to cache; this example will cache all JSP pages for 10 minutes in session scope):
    <filter>
        <filter-name>CacheFilter</filter-name>
        <filter-class>com.opensymphony.oscache.web.filter.CacheFilter</filter-class>
        <init-param>
            <param-name>time</param-name>
            <param-value>600</param-value>
        </init-param>
        <init-param>
            <param-name>scope</param-name>
            <param-value>session</param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>CacheFilter</filter-name>
        <url-pattern>*.jsp</url-pattern>
    </filter-mapping>
The default duration is one hour and the default scope for the cache is application scope. You can change these settings using initialization parameters. #### Example 2 The initialization of the last modified header based on the current time reduces transaction overhead and server load, because the browser can ask the server if the cached content in the browser cache was changed on the server since the last request. If the content wasn't changed , the server will response with the status 304 (not modified). Furthermore if the expires parameter is the set to time, the server will send the date and time after which the content is considered stale. Then common browsers won't request the server anymore until the cached content is considered stale. The example will cache the content for one hour by default and the expires date and time will be calculated based on the creation time and the time parameter (default is one hour).
    <filter>
        <filter-name>CacheFilterStaticContent</filter-name>
        <filter-class>com.opensymphony.oscache.web.filter.CacheFilter</filter-class>
        <init-param>
            <param-name>expires</param-name>
            <param-value>time</param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>CacheFilterStaticContent</filter-name>
        <url-pattern>*.jsp</url-pattern>
    </filter-mapping>
### Using the filter #### Example 1: ICacheKeyProvider A simple example how to use the ICacheKeyProvider parameter of the CacheFilter. The cache key in constructed with the http request URI and with two request parameters pageid and pagination.
    import javax.servlet.http.HttpServletRequest;

    import com.opensymphony.oscache.base.Cache;
    import com.opensymphony.oscache.web.ServletCacheAdministrator;
    import com.opensymphony.oscache.web.filter.ICacheKeyProvider;

    public class ExampleCacheKeyProvider implements ICacheKeyProvider {

        public String createCacheKey(HttpServletRequest httpRequest, ServletCacheAdministrator scAdmin, Cache cache) {

            // buffer for the cache key
            StringBuffer buffer = new StringBuffer(100);

            // part 1 of the key: the request uri
            buffer.append(httpRequest.getRequestURI());

            // separation
            buffer.append('_');

            // part 2 of the key: the page id
            buffer.append(httpRequest.getParameter("pageid"));

            // separation
            buffer.append('_');

            // part 3 of the key: the pagination
            buffer.append(httpRequest.getParameter("pagination"));

            return buffer.toString();
        }

    }
You can use session attributes values for the cache key also, if request parameters aren't available or e.g. security settings have to be add to the cache key. #### Example 2: Flush The flush example shows how to flush a CacheFilter with scope application based on group names. In this example the http servlet request of the user is required to get the cache object.
    import com.opensymphony.oscache.base.Cache;
    import com.opensymphony.oscache.web.ServletCacheAdministrator;

    import java.util.Collection;
    import java.util.Iterator;

    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.jsp.PageContext;

    public class OSCacheAdmin {

        /**
         * flush the CacheFilter according to dependent group
         *
         * @param request the HttpServletRequest of the user
         * @param groupNames a string collection of group names
         */
        public static void flushCacheGroup(HttpServletRequest request, Collection groupNames) {
        	Cache cache = ServletCacheAdministrator.getInstance(request.getSession().getServletContext()).getCache(request, PageContext.APPLICATION_SCOPE);
            Iterator groups = groupNames.iterator();
            while (groups.hasNext()) {
                String group = (String) groups.next();
                cache.flushGroup(group);
            }
        }
    }
If you're CacheFilter is running with scope session, you have to get the cache as follows:
    Cache cache = ServletCacheAdministrator.getInstance(request.getSession(true).getServletContext()).getCache(request, PageContext.SESSION_SCOPE);