Servlet Filters
Version 2.3 of the Servlet API introduced a new method of
handling requests using the javax.servlet.Filter
class. When
filters are used, the servlet container creates a
filter chain, which consists of zero or more
Filter
objects and a destination
resource, either a servlet or another resource available on the web
server (such as an HTML or JSP file).
Filters are installed in the server and associated with
particular request paths (just like servlets). When a filtered
resource is requested, the servlet constructs a filter chain and calls
the doFilter()
method of the first
filter in the filter chain, passing a ServletRequest
, a ServletResponse
, and the FilterChain
object. The filter can then
perform processing on the request. Filters are often used to implement
logging, control security, or set up connection-specific objects. A
filter can also wrap the ServletRequest
and ServletResponse
classes with its own
versions, overriding particular methods. For instance, one of the
example filters included with the Tomcat server adds support for
returning compressed output to browsers that support it.
After the filter has processed the response, it can call the
doFilter()
method of the FilterChain
to invoke the next filter in the
sequence. If there are no more filters, the request is passed on to
its ultimate destination. After calling doFilter()
, the filter can perform
additional processing on the response received from farther down the
chain.
In the event of an error, the filter ...
Get Java Enterprise in a Nutshell, Third 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.