Writing Servlet Filters

by Kief Morris kief@kief.com

Filters are an under-appreciated feature of the Java servlet platform, ideal for writing components that can be added transparently to any web application. A filter is like a lightweight servlet that doesn't generate its own content, instead it plugs into the request handling process and executes in addition to the normal page processing.

Filters might record information about requests, convert content to a different format, or even redirect access to a different page. Filters can be applied to any resources served by a servlet engine, whether it's flat HTML, graphics, a JSP page, servlet , or whatever. They can be added to an existing web application without either the filter or the application being aware of one another. Filters are essentially a server plug-in that works with any servlet container compliant with version 2.3 or later of the servlet specification.

A filter implements the interface javax.servlet.Filter, and configured in the web application web.xml file, where the URL's it will process are defined. For each request, the servlet container decides which filters to apply, and adds those filters to a chain in the same order they appear in web.xml. Each filter has its Filter.doFilter() method called, and triggers the invocation of the next filter in the chain or the loading of the final resource (HTML page, servlet, or whatever).

Writing a simple filter

To write a filter, we create a class implementing the Filter interface, which requires three methods: init(), doFilter(), and destroy(). init() and destroy() are called when the filter is first initialized and when it is destroyed, respectively, to allow configuration and cleanup. For the moment we'll ignore these and focus on doFilter(), which is the meat of the filter.


The servlet container calls the filter's doFilter() method and passes request and response objects for the current request. These are the same objects as a servlet gets, but since there is no HttpFilter, the parameters are defined as javax.servlet.ServletRequest and javax.servlet.ServletResponse, rather than the javax.servlet.http subclasses. This means that if you want to access methods available only on the HTTP versions of the request and response classes, you will need to cast the objects. To be a Good Programmer, you should first test that they actually are the HTTP versions, in case future generations want to use your filter in a non-HTTP servlet environment. Some of the code later in this article shows examples of this.

The third parameter to doFilter() is a FilterChain object, which is used to invoke the next filter in the chain. This is done by calling FilterChain.doFilter() and passing it the request and response objects. If the current filter is the last filter in the chain, the destination resource will be accessed, that is, the HTML page or other static file will be read in, or else a servlet or JSP page will be invoked. After FilterChain.doFilter() returns, the filter can do more processing if it chooses; at this point, the response object should have more fields populated, than it did beforehand, such as the content-type header having been set.

TimerFilter is a simple filter which does nothing more than time how long it takes to process the request after the filter, based directly on the Apache Foundation's Tomcat 4.0 server's ExampleFilter. If this filter is placed as the last filter in the chain, it times the servlet execution or page access itself. Here is the doFilter() method:

public final class TimerFilter implements Filter 

    public void doFilter(ServletRequest request, 
                         ServletResponse response,
                         FilterChain chain)
        throws IOException, ServletException 

        long startTime = System.currentTimeMillis();
        chain.doFilter(request, response);
        long stopTime = System.currentTimeMillis();
        System.out.println("Time to execute request: " + (stopTime - startTime) + 
            " milliseconds");


To compile a Filter you will need to link it with the servlet API classes, which include the interface definitions and other classes used by the filter. These classes are almost certainly available with your servlet container; typically named servlet.jar. If you download the sample source code for this article you can use Ant to compile the code; see the README.txt file for help on configuring the build.

Deploying a filter

To add a filter to a web application, you must first put the compiled filter class in the web application's classpath, which is normally done by putting it under WEB-INF/classes or in a jar file in WEB-INF/lib. The filter is then added to the WEB-INF/web.xml configuration file in much the same way a servlet is, in that there are two configuration blocks. The first defines the filter and gives it a name, and the second defines the circumstances in which the filter is invoked.

The <filter> configuration block

The filter class is defined with a <filter> block, which takes the following child elements:

filter-name The name which will be used to identify the filter elsewhere in the web.xml file.
filter-class The classname, including package, of the filter. This name will be used by the servlet container to load the filter class.
init-param Initialization parameters to pass to the filter. We'll discuss these shortly.
description Long description for the filter, this may be used by configuration tools also.
icon Optional paths to image files for GUI configuration tools to use to represent the filter.
display-name Optional descriptive text for the filter, mainly useful for configuration tools.

The only required elements are the name and class; the icon and display-name are pointless unless you're using a tool which uses them. Here is the configuration for the TimerFilter.

            This filter times the execution of the request after
            the filter itself, and prints the execution time to
            the standard output.

Note that the same filter class can be defined in multiple <filter> blocks, each with a different name. This creates a separate instance of the class for each <filter> block, each of which can have different configuration parameters.

0 Comments  (click to add your comment)
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



About | Sitemap | Contact