Difference between Filter and Listener in Servlet (Java EE)

100,391

Solution 1

Servlet Filter is used for monitoring request and response from client to the servlet, or to modify the request and response, or to audit and log.

Servlet Listener is used for listening to events in a web containers, such as when you create a session, or place an attribute in an session or if you passivate and activate in another container, to subscribe to these events you can configure listener in web.xml, for example HttpSessionListener.

Solution 2

Filters are used for pre and post process requests. Look at the javax.servlet.Filter in your tomcat/jboss/other container javadoc.

Where as the listeners are like triggers that can be attached to events in your app server (let's use the term container here). With listeners you can track application-level, session-level, life-cycle changes, attribute changes etc. The implemented interfaces are javax.servlet.Listener interface.

Based on @fnt 's responses below, let me try to clarify some more. Listeners are targeted for lifecycle changes, without having to have a client request coming in. So for one client request, there could be many more lifecycle events may happen before the request is disposed of. Example: You want to log all the sessions that timeout. Please note that SesionTimeout is a lifecycle event, which can happen without having the user to do anything. For such a scenario, a listener will be appropriate.

To the question of logging when a request arrives. There is no direct mapping of a new request to an equivalent listener (read lifecycle event) event. And hence for each incoming request if you want to log something, Filter in my opinion is the right thing to use.

This material from Oracle should be able to clarify some more Filters and Listeners

Update 17 Mar 2021 There has been some back and forth in the comments. Trying to clarify. By definition, a filter will always get invoked. So if i need to log the request ALWAYS, keeping it in filters will ensure that i get the logging. If i put it in listeners, i have to make sure the logging code block is executed in ALL possible listeners. Both approaches will get you the logging that you need, using filters will be more efficient.

HTH

Solution 3

Filter is just like a water filter, where incoming (request) and outgoing (response) values will be filtered.

Listener is like listening (trigger) - whenever required, I will be performed.

Solution 4

One important difference is often overlooked: while listeners get triggered for an actual physical request, filters work with servlet container dispatches. For one listener invocation there may be multiple filters/servlet invocations.

Listeners vs Filters

You can specify dispatcher types with the @WebFilter annotation:

import javax.servlet.DispatcherType;
import javax.servlet.annotation.WebFilter;

@WebFilter(servletNames = { "My Servlet" },
    dispatcherTypes = { DispatcherType.REQUEST, DispatcherType.FORWARD })

See Java EE 7 Tutorial: Filtering Requests and Responses for more information on filters.
If you still have trouble understanding filters, see Mapping filters dispatcher types - this is an older J2EE doc, but it goes into more detail.

Solution 5

Text from Java EE 6

Filter

Filter is an object which transform the request and response (header as well as content).

Listeners

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.

Share:
100,391

Related videos on Youtube

kandarp
Author by

kandarp

Sr. Java Developer, NetWeb Software Pvt. Ltd.

Updated on July 05, 2022

Comments

  • kandarp
    kandarp almost 2 years

    There are Filters and Listeners functionality in Servlet. I want to know exact difference between Filter and Listener.

  • dade
    dade over 10 years
    And it is also worth nothing that listeners implements javax.servlet.ServletContextListener while filters implement javax.servlet.Filter
  • arun
    arun over 9 years
    Can you pls clarify this for me? ServletRequestListener listens to ServletRequestEvent which is an event triggered for every incoming request. If I want to log the user-agent for every request to my web app, should I use this listener or a filter?
  • arun
    arun over 9 years
    So if one wants to log something about every request, should one use ServletRequestListener or a filter?
  • ᄂ ᄀ
    ᄂ ᄀ about 9 years
    @Ayusman Probably justification is required for this statement
  • Ayusman
    Ayusman about 9 years
    @fnt since arun asked for logging at per request basis I think filter will fit the bill.
  • ᄂ ᄀ
    ᄂ ᄀ about 9 years
    @Ayusman You still did not explain why filter should be preferred. With request listener one can equally accomplish the same.
  • Ayusman
    Ayusman about 9 years
    @fnt I don't know if this would be a satisfactory answer for you, but I will try: filters and listeners cater to different category of needs that is based on application boundary. Filters will cater to anything that is entering or leaving the application (an HttpRequest); where as Listeners cater to events with in the container. Visualize filters to be at the edge of an application, and listeners to be inside the application. Example: Web application login can be a "Authorization Filter" where as spring context inititalization is implemented as a lifecycle listener. HTH
  • ᄂ ᄀ
    ᄂ ᄀ almost 9 years
    @Ayusman I am sorry, but this does not help. Your reasoning is quite abstract to the topic and it is still not clear why filter should be preferred over listener for logging. Not to mention that you did not provide general principles which can be applied to drive the decision filter/listener.
  • Half Blood Prince
    Half Blood Prince almost 8 years
    @BalusC Is defining a listener is mandatory? It gives me error No WebApplicationContext found: no ContextLoaderListener registered? if I do not define a listener in my Spring application.
  • Mukul Tripathi
    Mukul Tripathi almost 8 years
    @fnt very good point, in my past experiences I have used filters for logging. Why? I think convention more than anything. Listeners can be used for this task as well though.
  • Ayusman
    Ayusman over 7 years
    @fnt Sorry for late reply. The key here is the question of logging for "every request". I have made some changes in my answer to be able to justify why filter instead of a listener.
  • Anuj Kumar
    Anuj Kumar over 5 years
    Filters act as pre and post hooks, they can modify the request and response. On the other hand, listeners are more like event handlers, they receive some event and react to it, they don't modify original event.
  • Jonathan Laliberte
    Jonathan Laliberte over 5 years
    hmm, i don't really get why you would need to listen for when a session is created or listen for when an attribute in a session is created. Can you give an example on when you've used a listener in any applications you've developed?
  • ᄂ ᄀ
    ᄂ ᄀ about 3 years
    @Ayusman Where is the justification really? The question was how to choose between filter and listener when it comes to logging. You merely added the description of how they work and did not address the question. You continue to use words like "appropriate" but fail to explain in which case listener will be inappropriate for logging and why.
  • ᄂ ᄀ
    ᄂ ᄀ about 3 years
    @Anuj Kumar So what? How is that relevant to the particular case of logging?
  • Ayusman
    Ayusman about 3 years
    The justification lies in the definition. Filters will guarantee that there will be logging whether a particular life cycle event was triggered or not. Since you want to log all requests coming in. It is possible that an incoming request may not necessarily trigger a life cycle event. Or you will end up duplicating the same logging code in every single lifecycle event + you might miss a logging if a particular lifecycle event did not get triggered. HTH