Servlet Filters

Servlets

A servlet container is a web browser that also manages a pool of servlets.

A servlet is a Java object that receives an HTTP request and generates an HTML response.

Of course a servlet may use the full power of Java to analyze the request and generate the response. This includes accessing databases, files, and application servers.

An HTTP request sent from a browser to a container may specify that information entered in a form should be processed by a specific servlet. In this case the container simply forwards the request to the desired servlet:

Filters

Sometimes we would like to preprocess requests before they reach a servlet and post process responses before they reach the browser.

We would like to do this without altering the servlet.

For example, we might like to localize the response, demand a password before forwarding the response to the servlet, or both.

The Decorator Design Pattern solves this problem by placing a chain of decorators in front of an object. Messages sent to the object must pass through each decorator in the chain. Decorators have the option of post processing the message before delegating it to the next member of the chain. The value returned by the object must also pass through the decorator chain. In this case each decorator has the option of post processing the return value.

Servlet containers use this pattern. Decorators are called filters.

A web programmer can define a filter and specify (in the web.xml file) that all requests sent to a particular servlet should first pass through this filter.

Of course there may be many filters for a particular servlet.

When the web application starts, the container creates a list of these filters. This is called a filter chain.

When the container receives a request from a browser specifying that form data should be processed by a specific servlet, it passes the request to the first filter in the filter chain for that servlet.

Each filter in the chain processes the request, then has the option of passing the request to the next filter in the chain.

After the last filter in the chain has processed the request, it is forwarded to the filter.

The servlet's response is passed back through the chain, where it may be processed by each filter before being sent back to the browser.

Here's a sequence diagram showing a filter chain consisting of two filters:

Examples

            The Auxiliary Stipend Calculator

References

Essentials of Filters (Sun)