ONJava.com -- The Independent Source for Enterprise Java
oreilly.comSafari Books Online.Conferences.

advertisement

AddThis Social Bookmark Button

Writing Servlet 2.3 Filters

by Stephanie Fesler
05/10/2001

This article is the third in a series dedicated to examining the new features of the Servlet 2.3 API specification. The first article was a high level introduction to Servlet concepts and the new features of the Servlet 2.3 specification: application lifecycle events and filters. The second article took a more in-depth look at writing and using application lifecycle events. Please read these articles for more information on those topics. This article covers how to write and use filters within your web applications, including examples of using a simple filter, configuring a filter chain, using initial parameters in a filter, parsing the user's request, and logging statistics.

Servlet filters are a new addition to the Servlet 2.3 specification that's in its public final draft stage, released in October, 2000. Filters are Java classes that can intercept requests from a client before they access a resource; manipulate requests from clients; intercept responses from resources before they are sent back to the client; and manipulate responses before they are sent to the client.

Filters have a wide array of uses; the Servlet 2.3 specification suggests the following uses:

  • authentication filters
  • logging and auditing filters
  • image conversion filters
  • data compression filters
  • encryption filters
  • tokenizing filters
  • filters that trigger resource access events
  • XSL/T filters that transform XML content
  • MIME-type chain filters

Writing a Simple Filter

The first step in learning how to write a filter is to look at a very simple example. A filter is simply a Java class that implements the javax.servlet.Filter interface. The javax.servlet.Filter interface defines three methods:

  • public void doFilter (ServletRequest request, ServletResponse response, FilterChain chain)
  • public FilterConfig getFilterConfig()
  • public void setFilterConfig (FilterConfig filterConfig)

It is the containers responsibility to create a javax.servlet.FilterConfig object and pass it to the filter during initialization. The javax.servlet.FilterConfig object can be used to

  • retrieve the filter name (as defined in the deployment descriptor),
  • retrieve the initial parameters (as defined in the deployment descriptor), and
  • get a reference to the ServletContext object the user is calling from.

The setFilterConfig() method can be used to capture the object into an attribute of the filter. The doFilter() method is where the filter's work is done, in which you can parse the user's request; log statistics to a file; manipulate the response back to the client; and so on. Listing 1 is an example of a very simple filter which prints a message to the console of the web server while it is filtering the request, calls the Servlet, and then prints another message to the console while it is filtering the response. Figure 1 is a diagram of how the simple filter fits into the servlet's request-response model.

Diagram of the simple filter.
Figure 1. A diagram of how the simple filter fits into the big picture.


Listing 1: An example of a very simple filter (SimpleFilter.java)

package com.filters;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import java.io.IOException;
import javax.servlet.ServletException;

public class SimpleFilter implements Filter
{
  private FilterConfig filterConfig;

  public void doFilter (ServletRequest request,
             ServletResponse response,
             FilterChain chain)
  {

    try
    {
      System.out.print ("Within Simple Filter ... ");
      System.out.println ("Filtering the Request ...");

      chain.doFilter (request, response);

      System.out.print ("Within Simple Filter ... ");
      System.out.println ("Filtering the Response ...");

    } catch (IOException io) {
      System.out.println ("IOException raised in SimpleFilter");
    } catch (ServletException se) {
      System.out.println ("ServletException raised in SimpleFilter");
    }
  }

  public FilterConfig getFilterConfig()
  {
    return this.filterConfig;
  }

  public void setFilterConfig (FilterConfig filterConfig)
  {
    this.filterConfig = filterConfig;
  }
}


As you can see the simple filter example is a Java class named SimpleFilter.java which implements the javax.servlet.Filter interface. It provides implementation for the three methods defined in the javax.servlet.Filter interface.

Notice that doFilter() can be separated into two sections: filtering the request and filtering the response. The two sections are separated by a call from the javax.servlet.FilterChain object to the next object in the chain, which could be the Servlet or another filter.

Now that we have written the filter, it might be nice to deploy it in a web server and see it in action.

Deploying Filters

Apache's Tomcat, version 4.0 beta, supports the Servlet 2.3 specification and all the examples in this article have been tested on that server.

Pages: 1, 2, 3, 4

Next Pagearrow