Servlet filtering

Servlet filtering is an integral part of the Servlet API. Servlet filtering provides a new type of object called a filter that can transform a request or modify a response.

You can chain filters together so that a group of filters can act on the input and output of a specified resource or group of resources.

Filters typically include logging filters, image conversion filters, encryption filters, and Multipurpose Internet Mail Extensions (MIME) type filters, which are functionally equivalent to the servlet chaining. Although filters are not servlets, their lifecycle is very similar.

Filters are handled in the following manner:

Filter, FilterChain, FilterConfig classes for servlet filtering

The following interfaces are defined as part of the javax.servlet package:

The following classes are defined as part of the javax.servlet.http package (see the J2EE 1.3 documentation for information about methods):

Example: com.ibm.websphere.LoggingFilter.java

The following example shows how to implement a filter:

package com.ibm.websphere;

import java.io.*;
import javax.servlet.*;

public class LoggingFilter implements Filter {

  File _loggingFile = null;

  // implement the required init method
  public void init(FilterConfig fc) {

    // create the logging file
      ...
  }

  // implement the required doFilter method.
  // this is where most of the work is done
  public void doFilter(ServletRequest request,
                       ServletResponse response,
                       FilterChain chain) {
    try {
      // add request info to the log file
      synchronized(_loggingFile) {
        ...
      }
 
      // pass the request on to the next resource in the chain
      chain.doFilter(request, response);
    }
    catch (Throwable t) {
      // handle problem...
    }
  }

  // implement the required destroy method
  public void destroy() {
    // make sure logging file is closed
    _loggingFile.close();
  }
}