What is the difference between a Servlet Filter and a Servlet Context Listener?
-
25-05-2021 - |
Question
What are the differences between using a Servlet Filter versus a Servlet Context Listener?
When would you use one or the other?
Solution
A Filter
intercepts on HTTP requests matching its URL pattern and allows you to modify them. See also its javadoc:
A filter is an object that performs filtering tasks on either the request to a resource (a servlet or static content), or on the response from a resource, or both.
Filters perform filtering in the
doFilter
method. EveryFilter
has access to aFilterConfig
object from which it can obtain its initialization parameters, and a reference to theServletContext
which it can use, for example, to load resources needed for filtering tasks.Filters are configured in the deployment descriptor of a web application.
Examples that have been identified for this design are:
- Authentication Filters
- Logging and Auditing Filters
- Image conversion Filters
- Data compression Filters
- Encryption Filters
- Tokenizing Filters
- Filters that trigger resource access events
- XSL/T filters
- Mime-type chain Filter
A ServletContextListener
intercepts on webapp's startup and shutdown and allows you to execute some code on startup and/or shutdown. See also its javadoc:
Interface for receiving notification events about
ServletContext
lifecycle changes.In order to receive these notification events, the implementation class must be either declared in the deployment descriptor of the web application, annotated with
WebListener
, or registered via one of theaddListener
methods defined onServletContext
.Implementations of this interface are invoked at their
contextInitialized(javax.servlet.ServletContextEvent)
method in the order in which they have been declared, and at theircontextDestroyed(javax.servlet.ServletContextEvent)
method in reverse order.
When to use the one or the other should now be obvious. Use a Filter
if you want to intercept on HTTP requests maching a specific URL pattern because you want to check/modify the HTTP request/response. Use a ServletContextListener
if you want to intercept on webapp's startup and/or shutdown.
Please know where to find the javadocs and how to interpret them. They contain all answers to this kind of trivial questions.