background image

Programming Filters

<< Filtering Requests and Responses | The doFilter() Method >>
<< Filtering Requests and Responses | The doFilter() Method >>

Programming Filters

Modify the request headers and data. You do this by providing a customized version of the
request.
Modify the response headers and data. You do this by providing a customized version of the
response.
Interact with external resources.
Applications of filters include authentication, logging, image conversion, data compression,
encryption, tokenizing streams, XML transformations, and so on.
You can configure a web resource to be filtered by a chain of zero, one, or more filters in a
specific order. This chain is specified when the web application containing the component is
deployed and is instantiated when a web container loads the component.
In summary, the tasks involved in using filters are
Programming the filter
Programming customized requests and responses
Specifying the filter chain for each web resource
Programming Filters
The filtering API is defined by the Filter, FilterChain, and FilterConfig interfaces in the
javax.servlet
package. You define a filter by implementing the
Filter
interface.
The most important method in this interface is doFilter, which is passed request, response,
and filter chain objects. This method can perform the following actions:
Examine the request headers.
Customize the request object if the filter wishes to modify request headers or data.
Customize the response object if the filter wishes to modify response headers or data.
Invoke the next entity in the filter chain. If the current filter is the last filter in the chain that
ends with the target web component or static resource, the next entity is the resource at the
end of the chain; otherwise, it is the next filter that was configured in the WAR. The filter
invokes the next entity by calling the doFilter method on the chain object (passing in the
request and response it was called with, or the wrapped versions it may have created).
Alternatively, it can choose to block the request by not making the call to invoke the next
entity. In the latter case, the filter is responsible for filling out the response.
Examine response headers after it has invoked the next filter in the chain.
Throw an exception to indicate an error in processing.
In addition to doFilter, you must implement the init and destroy methods. The init
method is called by the container when the filter is instantiated. If you wish to pass initialization
parameters to the filter, you retrieve them from the FilterConfig object passed to init.
Filtering Requests and Responses
Chapter 4 · Java Servlet Technology
115