Chapter 19. Filtering Requests and Responses


Servlet filtering was introduced with the servlet API v2.3 in 2001. Filtering is a powerful technology for servlet developers, who can use it to generate chains of Java classes that execute in sequence in response to client requests.

Developers begin by creating one or more Java classes that implement the javax.servlet.Filter interface. These classes can undertake a number of actions prior to a servlet’s request handling, creating a chain of actions before the request is delivered to its destination (including blocking the request altogether). These actions include, according to the Filter API documentation:

  • Authentication of requests

  • Data encryption

  • Data compression

  • Logging

  • Extensible Stylesheet Language Transformation (XSLT) filtering

  • Image conversion


Access the Javadoc for the Filter interface at:

Register a filter in the deployment descriptor, and then map the registered filter to either servlet names or URL patterns in your application’s deployment descriptor. When the web container starts up your web application, it creates an instance of each filter that you have declared in the deployment descriptor. The filters execute in the order that they are declared in the deployment descriptor.

19.1. Mapping a Filter to a Servlet


You want to map or apply a filter to an individual servlet.


Use the filter and filter-mapping elements in web.xml to associate ...

Get Java Servlet & JSP Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.