There are Filters and Listeners functionality in Servlet. I want to know exact difference between Filter and Listener.
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.
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.
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
HTH
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.
Mapping filters dispatcher types. The link is a bit dated - it doesn't include the Servlet 3.0 Async
dispatcher type.
One can also 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 })