Servlet Filtering and No-Cache

by Steven J. Owens (unless otherwise attributed)

Servlet Filtering to set the NoCache and Expires Header

This is a standard servlet filter (you know how to google, doncha?). Just compile it and deploy it. To deploy it, make sure your servlet web-app has the class file, put it in:


Then include the following in yourwebapp's WEB-INF/web.xml. Tweak the url-pattern element to indicate what files you want filtered. For example, let's say yourwebapp has a subdirectory named "/dev", for the in-development files that you don't want cached. You'd set the url-pattern to "/dev/*".


Here's the source for the NoCacheFilter class:

package com.darksleep ;

import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletRequest;

import; import javax.servlet.ServletException;

public class NoCacheFilter implements Filter {

public void init(FilterConfig config) throws ServletException { this.filterConfig = config; } private FilterConfig filterConfig; public FilterConfig getFilterConfig() { return this.filterConfig; } public void setFilterConfig (FilterConfig filterConfig) { this.filterConfig = filterConfig; } public void destroy() { this.filterConfig = null; }

public void doFilter (ServletRequest request, ServletResponse response, FilterChain chain) { try { if (response instanceof HttpServletResponse) { HttpServletResponse httpresponse = (HttpServletResponse)response ; // Set the Cache-Control and Expires header httpresponse.setHeader("Cache-Control", "no-cache") ; httpresponse.setHeader("Expires", "0") ; // Print out the URL we're filtering String name = ((HttpServletRequest)request).getRequestURI(); System.out.println("No Cache Filtering: " + name) ; } chain.doFilter (request, response); } catch (IOException e) { System.out.println ("IOException in NoCacheFilter"); e.printStackTrace() ; } catch (ServletException e) { System.out.println ("ServletException in NoCacheFilter"); e.printStackTrace() ; } } }

See original (unformatted) article


Verification Image:
Your Email Address:
Confirm Address:
Please Post:
Copyright: By checking the "Please Post" checkbox you agree to having your feedback posted on notablog if the administrator decides it is appropriate content, and grant compilation copyright rights to the administrator.
Message Content: