FileDocCategorySizeDatePackage
CacheFilter.javaAPI DocExample3238Sun Nov 23 17:43:06 GMT 2003cfexample.controller

CacheFilter

public class CacheFilter extends Object implements Filter
A filter that caches pages after they are generated.

Fields Summary
private FilterConfig
filterConfig
the filter configuration
private HashMap
cache
the cached data
Constructors Summary
public CacheFilter()
Constructor

    
          
      
    
Methods Summary
public voiddestroy()
Destroy the cache

        cache.clear();
        
        cache = null;
        filterConfig = null;
    
public voiddoFilter(javax.servlet.ServletRequest request, javax.servlet.ServletResponse response, javax.servlet.FilterChain chain)
Perform the actual caching. If a given key is available in the cache, return it immediately. If not, cache the result using a CacheResponseWrapper

        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
       
        // the cache key is the URI + query string
        String key = req.getRequestURI() + "?" + req.getQueryString();
        
        // only cache GET requests that contain cacheable data
        if (req.getMethod().equalsIgnoreCase("get") && isCacheable(key)) {
            // try to retrieve the data from the cache
            byte[] data = (byte[]) cache.get(key);
            
            // on a cache miss, generate the result normally and add it to the
            // cache
            if (data == null) {
                CacheResponseWrapper crw = new CacheResponseWrapper(res);
                chain.doFilter(request, crw);
                data = crw.getBytes();
                cache.put(key, data);
            } 
            
            // if the data was found, use it to generate the result
            if (data != null) {
                res.setContentType("text/html");
                res.setContentLength(data.length);
                
                try {
                    OutputStream os = res.getOutputStream();
                    os.write(data);
                    os.flush();
                    os.close();
                } catch(Exception ex) {
                    ex.printStackTrace();
                }
            }
        } else {
            // generate the data normally if it was not cacheable
            chain.doFilter(request, response);
        }
    
public voidinit(javax.servlet.FilterConfig filterConfig)
Initialize the cache

        this.filterConfig = filterConfig;
        
        cache = new HashMap();
    
private booleanisCacheable(java.lang.String key)
Return whether the given URI + query string is cacheable. A real implementation should use some kind of policy here.

        return true;