Chapter 19. Filtering Requests and Responses

Introduction

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

Tip

Access the Javadoc for the Filter interface at: http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/Filter.html.

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

Problem

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

Solution

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

Get Java Servlet & JSP Cookbook 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.