Using Filters and Listeners

The Servlet 2.3 specification introduced two component types beside servlets: filters and listeners.

Filters

A filter is a component that can intercept a request targeted for a servlet, JSP page, or static page, as well as the response before it’s sent to the client. This makes it easy to centralize tasks that apply to all requests, such as access control, logging, and charging for the content or the services offered by the application. A filter has full access to the body and headers of the request and response, so it can also perform various transformations. One example is compressing the response body if the Accept-Encoding request header indicates that the client can handle a compressed response.

A filter can be applied to either a specific servlet or to all requests matching a URL pattern, such as URLs starting with the same path elements or having the same extension. We look at the implementation and configuration of an access-control filter later in this chapter. You may also want to read Jason Hunter’s JavaWorld article about filters, http://www.javaworld.com/javaworld/jw-06-2001/jw-0622-filters.html.

In this article, he describes filters for measuring processing time, click and clickstreams monitoring, response compression, and file uploading.

Listeners

Listeners allow your application to react to certain events. Prior to Servlet 2.3, you could handle only session attribute binding events (triggered when an object was added or removed from a session). ...

Get JavaServer Pages, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.