public void | doFilter(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);
}
|