Saturday, April 22, 2023

Difference between Filter and Listener in Servlet - Java JEE

One of the frequently asked Servlet Interview question is what is the real difference between a Filter and a Listener? What is the role they play in a Java web application? In this article, I'll try to answer these question by explain what is Servlet Filter and Servlet Listener and what are their use in Java web application. A filter is used for pre-processing and post-processing. It can intercept the request before it hits to the servlet and can modify both header and body of Servlet, hence it is used to perform login, authentication, authorization and other security aspect which is require before client can access the resource e.g. a Servlet or JSP. Similarly, filters can also intercept the response and modify both header and body of response, hence you can use it both compress and encrypt the response before sending it to the client. 

You can also create a chain of filters where each filter in the chain will invoke next filter until it reach the end of the chain where request is passed to the resource like Servlet. Spring security's chain of filters is a good example of that. 

On the hand, Servlet Listeners are used to listen for life-cycle events and act accordingly. There are separate kind of listeners to listen different events e.g. there is ServletContextListener which listens for Servlet context event wrapped in ServletContextEvent object e.g. when a context is created or destroyed, or HttpSessionListener which listens for HttpSessionEvent and receives callback when an Http Session is created or about to be invalidated. You can use these callback method to perform cleanup job. 

A good example of Servlet listener is the Spring's ContextLoaderListener class, which implements ServletContextListener and creates Spring bean when ServletContext is created (when server is started and application is deployed) and destroy them when context is destroyed i.e. when application is undeployed or server is shut down. 


Servlet Filter vs Servlet Listener

Before looking for differences between a Servlet Filter and a Servlet Listener, let's first see some similarities. This will help you to understand their differences better:

1) Both Listener and Filter are declared in deployment descriptor or web.xml

2) Both are required to implement certain interfaces so that web container can give them call back. 

Now, let's see some key differences between a Filter and a Listener in Servlet framework:

1. Declaration and Lifecycle

Filters are declared using <filter> tag in web.xml while Listener's are declared using <listener> tag. Similar to Servlet's Filters are also use url-pattern to intercept incoming request. When a filter's URL pattern matches with the incoming request then Servlet container e.g. Tomcat create instance of Filter and passes the request to it. 

Filter does its processing and then pass it to the next filter in chain of the Servlet itself. Here is an example of how to declare a Filter and a Listener into deployment descriptor or web.xml file in Java:

<web-app>

<!-- declaring a listener in web.xml -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<servlet> 
<servlet-name>Servlet1</servlet-name> 
<servlet-class>HelloServlet</servlet-class> 
</servlet> 
<servlet-mapping> 
<servlet-name>Servlet1</servlet-name> 
<url-pattern>/servlet1</url-pattern> 
</servlet-mapping> 

<filter> 
<filter-name>Filter1</filter-name> 
<filter-class>MyFilter</filter-class> 
</filter> 

<filter-mapping> 
<filter-name>Filter1</filter-name> 
<url-pattern>/servlet1</url-pattern> 
</filter-mapping> 

</web-app>

On the other hand, Listeners are created when application is deployed and Servlet Container sends notification when an interesting event is triggered. 

For example, if listener class is listening for ServletRequestEvent then they will be notified every time a request is initialized. Since servlet container initialize the request, it also notifies to any listener registered for such event. It's basically Observer design pattern (See GOF Design Pattern book) for more details. 

Difference between Filter and Listener in Servlet - Java JEE



2. Implementation

Every Filters implement javax.servlet.Filter interface, while listener can implement different interfaces depending upon which kind of event they want to listen. For example, if you are interested on servlet context events then your listen need to implement javax.servlet.ServletContextListener.

Similarly, if you are interested on listening HTTP session events then your listener class needs to implement javax.servlet.HttpSessionListener

Other useful listener interfaces from javax.servlet and javax.servlet.http package is ServletRequestListener, which listens for events like request initialization and destroy, and HttpSessionAttributeListener, which listens for events when a session attribute is added, replaced, or removed in http session. See Head First Servlet and JSP for more details. 

This is an extension of above point. Every filter needs to override just one doFilter() method but you need to override multiple methods depending upon which event you are interested in.

For example, if you are interested in when http session is created and destroyed then you need to implement HttpSessionListener and override sessionCreated(HttpSessionEvent se) and sessionDestroyed(HttpSessionEvent se). You will receive notification in these method when a session was created and when a session is about to be invalidated.

Spring security filter chain



3. Usage

Filters are generally used for pre-processing of ServletRequest and post-processing of ServletResponse. You can use filter to implement sophisticated functionality e.g. security aspects like authentication and authorization. 

Spring Security's security filter chain is a good example of using filter to implement security for web application. You can also create filter for counting number of request, compressing response before sending to client etc. 

A filter has access both headers and body of ServletRequest and ServletResponse. 

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

On the other hand, Servlet listeners are used to listen for life-cycle event and act accordingly. A good example of using Servlet listener is the Spring MVC framework's ContextLoaderListener which implements javax.servlet.ServletContextListener and listen for ServletContextEvent e.g. when context is created and when context is destroyed, accordingly it creates Spring bean and clean them up.

You can implement HttpSessionListener to listen for http session creation and invalidation to implement auto-logout functionality for your application.

How filter chain works in Servlet




4. FilterChain

You can create a chain of filters in Servlet based Java web application where each filter forward request to next filter in chain and finally to the servlet which is suppose to process the request. The javax.servlet.FilterChain class is used to create filter chain. 

Filters use the FilterChain to invoke the next filter in the chain, or if the calling filter is the last filter in the chain, to invoke the resource at the end of the chain.

Spring Security's security filter chain is a good example of chain of filters implementing different security aspects. This sort of functionality is not available for listeners. 

Difference between Filter and Listener


That's all about difference between Servlet Filter and Servlet Listener in Java or JEE. Just remember that Filter is used for pre-processing and post-processing of request and response e.g. they are used to implement security related features e.g. authentication and authorization. Spring Security's security filter chain is a good example of that. 

On the other hand, Servlet Listener is used to listen for life-cycle event and act accordingly. For example, Spring's ContextLoaderListener implements ServletContextListener and creats Spring managed bean when context is created and clean them up when context is destroyed. It receives callback on contextCreated(ServletContextEvent sce) and contextDestroyed(ServletContextEvent sce) when such event happen. 

These are just a couple of popular example, there are many sophisticated usage of both Filter and Listener in Java EE world e.g. you can also de-register connection pool when context is destroyed to avoid potential memory leak due to DB connection pool keeping reference of Servlet classes. 

There are also listener which can listen for HttpSessionEvent e.g. when session is created, when session is timed out, you can perform a lot of clean-job with respect to user's session by listening for those events. 


Other Spring Articles and Resources you may like:
  • Difference between @Compoent, @Service, and @Controller in Spring? (answer)
  • Top 5 Spring and Hibernate Training courses (courses)
  • 15 Spring Boot Interview Questions with Answers (questions)
  • Difference between @Autowired and @Inject in Spring? (answer)
  • 20 REST with Spring Interview Questions for Web developers (questions)
  • 6 Resources to learn Spring Framework in Depth (resources)
  • Top 5 Courses to learn Microservices in Spring? (courses)
  • Difference between @RequestParam and @PathVariable in Spring (answer)
  • 5 Spring Framework Books For Java Developers (books)
  • 5 Spring Boot Features Java developer should learn (features)
  • 10 Advanced Spring Boot Courses for Java developers (courses)
  • 3 ways to learn Core Spring or Spring MVC better (article)
  • Top 10 Spring Framework Interview Questions (questions)
  • 5 Free Spring Framework and Spring Boot Courses (courses)
  • 10 Spring MVC Annotations Every Java Dev should know (annotations)


Further Reading
  • Java Web Fundamentals
  • Head First Servlet and JSP
  • Servlt Interview Questions
  • Oracle Certified Java EE Web Developer Certification
  • Servlet and JSP books

Thanks for reading this article so far. If you like this interview question and my explanation then please share with your friend and colleagues. If you have any question or suggestion then please drop a comment and I'll try to find an answer for you.

No comments:

Post a Comment