Filter vs Listener

This article briefly shows the main differences between Filter an Listener in Java.

Servlet Filter

Filter is an object which transform the request and response (header as well as content).
Servlet Filter is used for manipulating the request and response from client to the servlet, or to modify the request and response, or to audit and log. Filters are called on a per-request basis and listeners are not. Filters have access to request object and listeners don’t. Filters can perform many different types of functions. We’ll discuss examples of the italicized items in this paper:

  • Authentication-Blocking requests based on user identity.
  • Logging and auditing-Tracking users of a web application.
  • Image conversion-Scaling maps, and so on.
  • Data compression-Making downloads smaller.
  • Localization-Targeting the request and response to a particular locale.
  • XSL/T transformations of XML content-Targeting web application responses to more that one type of client.

Servlet Listener

You can monitor and react to events in a servlet’s life cycle by defining listener objects whose methods get invoked when life cycle events occur. Servlet Listener is used for listening various events inside a web containers, such as when you create a session, or place an attribute in a session or if you passivate and activate in another container, to manipulate these events you can configure listener in web.xml, for example HttpSessionListener. Below a list of provided Listener classes:

  • HttpSessionAttributeListener
  • HttpSessionBindingListener
  • HttpSessionListener
  • ServletContextAttributeListener
  • ServletContextListener

If you want to learn more retro games news, read our magazine and subscribe to our newsletter.