kandarp
kandarp

Reputation: 5047

Difference between Filter and Listener in Servlet (Java EE)

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

Upvotes: 83

Views: 104758

Answers (12)

Anish Karthik
Anish Karthik

Reputation: 17

If you're talking about authorization specific to certain resources, such as verifying a request to path like this:

/users/:userId/accounts/:accId

You can handle common authorization in a filter, for eg, verifying if the :userId in the path matches the current session’s userId. In this case, a filter is appropriate, even if it requires a lightweight database query (such as fetching the user information).

However, if you need to verify that the :accId belongs to the specific :userId, you may want to query the database to retrieve the account resource and then check if acc.userId == params.userId.

This type of resource-specific validation (fetching and verifying) is better suited to be handled in the servlet itself. If you decide to handle this in the filter:

  1. You may end up making an extra DB call, which can be inefficient if you need the account details again in the servlet.
  2. Each path, route, and method would require separate filters or validation logic, which makes the filter layer more complex and less reusable. This is why it’s better to perform these specific and complex tasks in the servlet, under the matching HTTP method and path, where the business logic is more modular and context-specific.

In summary:

Use filters for common authorization/validation tasks that apply across multiple paths or servlets (like verifying if the session userId matches the path parameter userId). Use servlets for specific resource validation and business logic, especially when the validation involves querying the database and checking resource ownership (like checking if :accId belongs to :userId).

Generally, if you have common concerns across different paths and methods, handle them in a filter. For more specific and complex validations, I prefer handling them in the servlet.

Upvotes: 0

Charlie Reitzel
Charlie Reitzel

Reputation: 925

Mostly the answers have this topic covered. But I find there are a couple practical differences between using Filter vs. ServletRequestListener.

The 1st is that the listener never gets access to a servlet response object. Thus, you have to use a Filter to get access HTTP status returned to the external caller.

Second, all the listeners will have their respective requestInitialized methods called before the 1st filter is fired. Likewise, the listeners' requestDestroyed methods are called after the last filter is done.

So, to be sure some request attribute is available to all filters, using a listener avoids having to play games with filter ordering.

Likewise, for removing that attribute / tearing down some shared resource, using the listener requestDestroyed method ensures all filters are done with it regardless of what order they run.

Upvotes: 0

Vsevolod Golovanov
Vsevolod Golovanov

Reputation: 4206

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.

Upvotes: 25

Ayusman
Ayusman

Reputation: 8719

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

Upvotes: 38

Abimaran Kugathasan
Abimaran Kugathasan

Reputation: 32468

You can easily have a rough idea with the English meaning of those two.

Filter is there to filter the content/resource which coming to/going out from a Servlet. In the other hand, Listener is there, to do some related things when something happen to the web application(listening).

Upvotes: 3

Code Guru
Code Guru

Reputation: 15578

After reading all the answers and blogs this is what I got

Filter

A filter is an object that dynamically intercepts requests and responses to transform or use the information contained in the requests or responses.

Filters typically do not themselves create responses but instead provide universal functions that can be "attached" to any type of servlet or JSP page.

The filter is run before rendering view but after controller rendered response.

A Filter is used in the web layer only as it is defined in web.xml.

Filters are more suitable when treating your request/response as a black box system. They'll work regardless of how the servlet is implemented.

Filters are used to perform filtering tasks such as login authentication ,auditing of incoming requests from web pages, conversion, logging, compression, encryption and decryption, input validation etc.

A Servlet Filter is used in the web layer only, you can't use it outside of a web context.

For more detail on filter http://array151.com/blog/servlet-filter/

Listener

Servlet Listener is used for listening to events in a web container, such as when you create a session or place an attribute in a 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.

Listeners get triggered for an actual physical request that can be attached to events in your app server .With listeners, you can track application-level, session-level, life-cycle changes, attribute changes etc.

You can monitor and react to events in a servlet's life cycle by defining listener objects whose methods get invoked when lifecycle events occur.

For more detail : http://array151.com/blog/servlet-listener/

and here is the difference http://array151.com/blog/difference-between-servlet-filter-and-servlet-listener/

Upvotes: 9

muhammed Younus attari
muhammed Younus attari

Reputation: 381

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.

Upvotes: 25

Mawia
Mawia

Reputation: 4310

In short,

Filter is for the Servlet, intercepting the requests and responses.

Listener is for the Web Application, doing important tasks on events in context-level, session-level etc.

Upvotes: 1

geet
geet

Reputation: 21

Filter:Filter is simply Filtering the Response and request coming from the clients to the servlet.

Listener:is like a trigger when any trigger is occur it take the action.

Upvotes: 2

Dead Programmer
Dead Programmer

Reputation: 12575

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.

Upvotes: 86

KV Prajapati
KV Prajapati

Reputation: 94645

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.

Upvotes: 11

Clyde Lobo
Clyde Lobo

Reputation: 9174

While you can modify the current event object within a listener, you cannot halt the execution of the current event handler in a listener. You also cannot clear the event queue from within a listener. Besides the imposed differences in capabilities, they are also intended for different purposes. Listeners tend to focus on interacton between the event handler and the model, while filters tend to focus on interaction between the event handler and the controller.

Source : web

Upvotes: 4

Related Questions