Tuesday, May 7, 2024
HomeJavaDistinction between Filter and Listener in Servlet

Distinction between Filter and Listener in Servlet


One of many regularly requested Servlet Interview query is what’s the actual distinction between a Filter and a Listener? What’s the position they play in a Java net utility? On this article, I will attempt to reply these query by clarify what’s Servlet Filter and Servlet Listener and what are their use in Java net utility. A filter is used for pre-processing and post-processing. It might probably intercept the request earlier than it hits to the servlet and might modify each header and physique of Servlet, therefore it’s used to carry out login, authentication, authorization and different safety side which is require earlier than consumer can entry the useful resource e.g. a Servlet or JSP

Equally, filters may also intercept the response and modify each header and physique of response, therefore you should use it each compress and encrypt the response earlier than sending it to the consumer. 

On the hand, Servlet Listeners are used to pay attention for life-cycle occasions and act accordingly. There are separate type of listeners to pay attention totally different occasions e.g. there’s ServletContextListener which listens for Servlet context occasion 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 need to use these callback technique to carry out cleanup job. 
A great instance of Servlet listener is the Spring’s ContextLoaderListener class, which implements ServletContextListener and creates Spring bean when ServletContext is created (when server is began and utility is deployed) and destroy them when context is destroyed i.e. when utility is undeployed or server is shut down. 

Servlet Filter vs Servlet Listener

Earlier than in search of variations between a Servlet Filter and a Servlet Listener, let’s first see some similarities. This can enable you to grasp their variations higher:

1) Each Listener and Filter are declared in deployment descriptor or net.xml

2) Each are required to implement sure interfaces in order that net container can provide them name again. 

Now, let’s examine some key variations between a Filter and a Listener in Servlet framework:

1. Declaration and Lifecycle

Filters are declared utilizing <filter> tag in net.xml whereas Listener’s are declared utilizing <listener> tag. Just like Servlet’s Filters are additionally use url-pattern to intercept incoming request. When a filter’s URL sample matches with the incoming request then Servlet container e.g. Tomcat create occasion of Filter and passes the request to it. 
Filter does its processing after which move it to the subsequent filter in chain of the Servlet itself. Right here is an instance of how one can declare a Filter and a Listener into deployment descriptor or net.xml file in Java:
<web-app>


<listener>
<listener-class>org.springframework.net.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>

Then again, Listeners are created when utility is deployed and Servlet Container sends notification when an fascinating occasion is triggered. 

For instance, if listener class is listening for ServletRequestEvent then they are going to be notified each time a request is initialized. Since servlet container initialize the request, it additionally notifies to any listener registered for such occasion. It is principally Observer design sample (See GOF Design Sample guide) for extra particulars. 
Difference between Filter and Listener in Servlet - Java JEE

2. Implementation

Each Filters implement javax.servlet.Filter interface, whereas listener can implement totally different interfaces relying upon which type of occasion they need to pay attention. For instance, in case you are on servlet context occasions then your pay attention must implement javax.servlet.ServletContextListener.

Equally, in case you are on listening HTTP session occasions then your listener class must implement javax.servlet.HttpSessionListener

Different helpful listener interfaces from javax.servlet and javax.servlet.http bundle is ServletRequestListener, which listens for occasions like request initialization and destroy, and HttpSessionAttributeListener, which listens for occasions when a session attribute is added, changed, or eliminated in http session. See Head First Servlet and JSP for extra particulars. 

That is an extension of above level. Each filter must override only one doFilter() technique however you want to override a number of strategies relying upon which occasion you have an interest in.

For instance, in case you are fascinated by when http session is created and destroyed then you want to implement HttpSessionListener and override sessionCreated(HttpSessionEvent se) and sessionDestroyed(HttpSessionEvent se). You’ll obtain notification in these technique when a session was created and when a session is about to be invalidated.

Spring security filter chain

3. Utilization

Filters are usually used for pre-processing of ServletRequest and post-processing of ServletResponse. You need to use filter to implement subtle performance e.g. safety elements like authentication and authorization. 

Spring Safety’s safety filter chain is an effective instance of utilizing filter to implement safety for net utility. You too can create filter for counting variety of request, compressing response earlier than sending to consumer and so on. 

A filter has entry each headers and physique of ServletRequest and ServletResponse. 

On the whole, Filters are used to carry out filtering duties comparable to safety, authentication ,auditing of incoming requests from net pages, conversion, logging, compression, encryption and decryption, enter validation and so on.

Then again, Servlet listeners are used to pay attention for life-cycle occasion and act accordingly. A great instance of utilizing Servlet listener is the Spring MVC framework’s ContextLoaderListener which implements javax.servlet.ServletContextListener and pay attention for ServletContextEvent e.g. when context is created and when context is destroyed, accordingly it creates Spring bean and clear them up.

You possibly can implement HttpSessionListener to pay attention for http session creation and invalidation to implement auto-logout performance in your utility.

How filter chain works in Servlet

4. FilterChain

You possibly can create a series of filters in Servlet primarily based Java net utility the place every filter ahead request to subsequent filter in chain and eventually to the servlet which is suppose to course of the request. The javax.servlet.FilterChain class is used to create filter chain. 

Filters use the FilterChain to invoke the subsequent filter within the chain, or if the calling filter is the final filter within the chain, to invoke the useful resource on the finish of the chain.

Spring Safety’s safety filter chain is an effective instance of chain of filters implementing totally different safety elements. This type of performance isn’t out there for listeners. 

Difference between Filter and Listener

That is all about distinction between Servlet Filter and Servlet Listener in Java or JEE. Simply do not forget that Filter is used for pre-processing and post-processing of request and response e.g. they’re used to implement safety associated options e.g. authentication and authorization. Spring Safety’s safety filter chain is an effective instance of that. 

Then again, Servlet Listener is used to pay attention for life-cycle occasion and act accordingly. For instance, Spring’s ContextLoaderListener implements ServletContextListener and creats Spring managed bean when context is created and clear them up when context is destroyed. It receives callback on contextCreated(ServletContextEvent sce) and contextDestroyed(ServletContextEvent sce) when such occasion occur. 

These are simply a few in style instance, there are a lot of subtle utilization of each Filter and Listener in Java EE world e.g. you may also de-register connection pool when context is destroyed to keep away from potential reminiscence leak because of DB connection pool maintaining reference of Servlet courses. 

There are additionally listener which may pay attention for HttpSessionEvent e.g. when session is created, when session is timed out, you’ll be able to carry out quite a lot of clean-job with respect to consumer’s session by listening for these occasions. 

Different Spring Articles and Sources chances are you’ll like:

  • Distinction between @Compoent, @Service, and @Controller in Spring? (reply)
  • Prime 5 Spring and Hibernate Coaching programs (programs)
  • 15 Spring Boot Interview Questions with Solutions (questions)
  • Distinction between @Autowired and @Inject in Spring? (reply)
  • 20 REST with Spring Interview Questions for Net builders (questions)
  • 6 Sources to study Spring Framework in Depth (assets)
  • Prime 5 Programs to study Microservices in Spring? (programs)
  • Distinction between @RequestParam and @PathVariable in Spring (reply)
  • 5 Spring Framework Books For Java Builders (books)
  • 5 Spring Boot Options Java developer ought to study (options)
  • 10 Superior Spring Boot Programs for Java builders (programs)
  • 3 methods to study Core Spring or Spring MVC higher (article)
  • Prime 10 Spring Framework Interview Questions (questions)
  • 5 Free Spring Framework and Spring Boot Programs (programs)
  • 10 Spring MVC Annotations Each Java Dev ought to know (annotations)

Additional Studying

  • Java Net Fundamentals
  • Head First Servlet and JSP
  • Servlt Interview Questions
  • Oracle Licensed Java EE Net Developer Certification
  • Servlet and JSP books

Thanks for studying this text to date. In case you like this interview query and my clarification then please share along with your good friend and colleagues. If in case you have any query or suggestion then please drop a remark and I will attempt to discover a solution for you.



RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments