Spring Boot + Servlet Listener

By Arvind Rai, December 04, 2023
We register servlet listeners in Spring Boot using either ServletListenerRegistrationBean or @Component or @ServletComponentScan. ServletListenerRegistrationBean class registers servlet listeners as Spring bean. @ServletComponentScan annotation scans servlet listeners annotated with @WebListener and it works only when using embedded server. In our example, we will create listeners using HttpSessionListener and ServletContextListener and provide complete example to register them in Spring Boot.

1. Register Listener with ServletListenerRegistrationBean

ServletListenerRegistrationBean registers a servlet Listener as Spring bean. ServletListenerRegistrationBean provides setListener() method to assign the listener. Suppose we have listeners as following.
SessionCountListener.java
public class SessionCountListener implements HttpSessionListener {
	private final AtomicInteger sessionCount = new AtomicInteger();
	@Override
	public void sessionCreated(HttpSessionEvent se) {
		sessionCount.incrementAndGet();
		setActiveSessionCount(se);
	}
	@Override
	public void sessionDestroyed(HttpSessionEvent se) {
		sessionCount.decrementAndGet();
		setActiveSessionCount(se);
	}
	private void setActiveSessionCount(HttpSessionEvent se) {
		se.getSession().getServletContext()
		   .setAttribute("activeSessions", sessionCount.get());
		System.out.println("Total Active Session: " + sessionCount.get());
	}
} 
AdminInfoListener.java
public class AdminInfoListener implements ServletContextListener {
	@Override
	public void contextInitialized(ServletContextEvent sce) {
		System.out.println("ServletContextEvent initialized.");
		ServletContext sc = sce.getServletContext();
		sc.setAttribute("admin", "Krishna");
	}
	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		ServletContext sc = sce.getServletContext();
		sc.removeAttribute("admin");
		System.out.println("ServletContextEvent destroyed.");			
	}
} 
Now in JavaConfig, we will use ServletListenerRegistrationBean class to register our listeners as Spring bean.
WebConfig.java
@Configuration
public class WebConfig {
   //Register SessionCountListener	
   @Bean
   public ServletListenerRegistrationBean<SessionCountListener> sessionCountListener() {
	   ServletListenerRegistrationBean<SessionCountListener> listenerRegBean = new ServletListenerRegistrationBean<>();
	   listenerRegBean.setListener(new SessionCountListener());
	   return listenerRegBean;
   }
   //Register AdminInfoListener	
   @Bean
   public ServletListenerRegistrationBean<AdminInfoListener> adminInfoListener() {
	   ServletListenerRegistrationBean<AdminInfoListener> listenerRegBean = new ServletListenerRegistrationBean<>();
	   listenerRegBean.setListener(new AdminInfoListener());
	   return listenerRegBean;
   }   
   ------
} 

2. Register Listener with @Component

We can register servlet listeners in Spring Boot by annotating it with Spring @Component as following.
SessionCountListener.java
@Component
public class SessionCountListener implements HttpSessionListener {
   ------
} 
AdminInfoListener.java
@Component
public class AdminInfoListener implements ServletContextListener {
   ------
} 

3. Register Listener with @ServletComponentScan and @WebListener

We can register servlet listeners using @ServletComponentScan with @Configuration or @SpringBootApplication annotations. The servlet listeners annotated with @WebListener will be scanned by @ServletComponentScan. It also scans servlets and filters annotated with @WebServlet and @WebFilter respectively. @ServletComponentScan works only when using embedded server. Find the sample listeners annotated with @WebListener.
SessionCountListener.java
@WebListener
public class SessionCountListener implements HttpSessionListener {
   ------
} 
AdminInfoListener.java
@WebListener
public class AdminInfoListener implements ServletContextListener {
   ------
} 
Now use @ServletComponentScan with @SpringBootApplication in Main class as following.
SpringBootAppStarter.java
@ServletComponentScan
@SpringBootApplication
public class SpringBootAppStarter {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootAppStarter.class, args);
    }
} 

4. Output

Download the source code and test the application. Run the following URL.
http://localhost:8080/app/country 
We will get following output in browser.
Output
Hello India!
Admin: Krishna
Total Active Session: 1 

5. References

Class ServletListenerRegistrationBean
Spring Boot Reference Guide

6. Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE












©2024 concretepage.com | Privacy Policy | Contact Us