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.

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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access