A Filter
intercepts HTTP requests that match the URL pattern and allows you to modify them. See also javadoc :
A filter is an object that performs filtering tasks either for a resource request (servlet or static content), or for a response from a resource, or both.
Filters perform filtering in the doFilter
method. Each Filter
has access to the FilterConfig
object, from which it can get its initialization parameters, and a link to the ServletContext
, which it can use, for example, to load resources necessary for filtering tasks.
Filters are configured in the deployment descriptor of the web application.
Examples that were defined for this project:
- Authentication Filters
- Registration and audit filters
- Image Conversion Filters
- Data compression filters
- Filter Encryption
- Filter designation
- Filters that trigger resource access events
- XSL / T Filters
- Mime type chain
A ServletContextListener
intercepts the start and end of the webapp and allows you to execute some code at startup and / or shutdown. See also javadoc :
Interface for receiving notifications of changes in the ServletContext
life cycle.
To receive these notification events, the implementation class must be declared in the deployment descriptor of the web application, annotated using the WebListener
or registered using one of the addListener
methods defined in ServletContext
.
Implementations of this interface are called using the contextInitialized(javax.servlet.ServletContextEvent)
method contextInitialized(javax.servlet.ServletContextEvent)
in the order in which they were declared, and using the contextDestroyed(javax.servlet.ServletContextEvent)
method contextDestroyed(javax.servlet.ServletContextEvent)
in the reverse order.
When to use one or the other, it should now be obvious. Use Filter
if you want to intercept HTTP requests while processing a specific URL pattern, because you want to check / modify the HTTP request / response. Use ServletContextListener
if you want to intercept start and / or shutdown with webapp.
Find out where to find javadocs and how to interpret them. They contain answers to all trivial questions.