Question

What are the differences between using a Servlet Filter versus a Servlet Context Listener?

When would you use one or the other?

Was it helpful?

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. Every Filter has access to a FilterConfig object from which it can obtain its initialization parameters, and a reference to the ServletContext 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 the addListener methods defined on ServletContext.

Implementations of this interface are invoked at their contextInitialized(javax.servlet.ServletContextEvent) method in the order in which they have been declared, and at their contextDestroyed(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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top