Servlet Filters

Version 2.3 of the Java servlet specification adds a new feature called filters . A filter is an object that intercepts requests to a servlet, JSP, or static file in a web application. The filter has the opportunity to modify the request before passing it along to the underlying resource and can capture and modify the response before sending it back to the client. Since filters can be specified declaratively using the web application deployment descriptor, they can be inserted into existing web applications without altering any of the existing code.

Filter Overview

Servlet filters are useful for many purposes, including logging, user authentication, data compression, encryption, and XSLT transformation. Many filters can be chained together, each performing one specific task. For the purposes of this book, XSLT transformations are the most interesting use of filters. Figure 8-5 illustrates the general filter architecture.

Servlet filters

Figure 8-5. Servlet filters

javax.servlet.Filter is an interface that all custom filters must implement. It defines the following three methods:

void init(FilterConfig config)
void destroy(  )
void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)

The init( ) and destroy( ) methods are virtually identical to the init( ) and destroy( ) methods found in any servlet. init( ) is called when the filter is first loaded, and the FilterConfig ...

Get Java and XSLT 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.