by Steven J. Owens (unless otherwise attributed)
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:
tomcathome/webapps/yourwebapp/WEB-INF/classes/com/darksleep/NoCacheFilter.class
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/*".
<filter> <filter-name>NoCacheFilter</filter-name> <filter-class>com.darksleep.NoCacheFilter</filter-class> </filter> <filter-mapping> <filter-name>NoCacheFilter</filter-name> <url-pattern>/dev/*</url-pattern> </filter-mapping>
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 java.io.IOException; 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() ; } } }