[Spring Boot] Spring Boot Listener | Servlet listener

Keywords: Java Spring Spring Boot listener

This page will introduce an example of the Spring Boot listener.

We can register Servlet listeners in Spring Boot using ServletListenerRegistrationBean or @ Component or @ ServletComponentScan.

The ServletListenerRegistrationBean class registers the Servlet listener as a Spring Bean.

@The ServletComponentScan annotation scans servlet listeners annotated with @ WebListener, which only works when using an embedded server.

In our example, we will use httpsessionlister and ServletContextListener to create listeners and provide complete examples to register them in Spring Boot.

1. Example tool version

  1. Java 9
  2. Spring 5.0.7.RELEASE
  3. Spring Boot 2.0.3.RELEASE
  4. Maven 3.5.2
  5. Eclipse Oxygen

2. Register the listener with ServletListenerRegistrationBean

ServletListenerRegistrationBean registers a Servlet listener as a Spring Bean.

ServletListenerRegistrationBean provides the setListener() method to assign listeners. Suppose we have the following listeners.

SessionCountListener.java

public class SessionCountListener implements HttpSessionListener {
  ------
} 

AdminInfoListener.java

public class AdminInfoListener implements ServletContextListener {
   ------
} 

Now in JavaConfig, we will use the ServletListenerRegistrationBean class to register our listener as a 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;
   }   
   ------
} 

3. Register the listener with @ Component

We can register servlet listeners in Spring Boot by using the Spring @Component annotation, as shown below.

SessionCountListener.java

@Component
public class SessionCountListener implements HttpSessionListener {
   ------
} 

AdminInfoListener.java

@Component
public class AdminInfoListener implements ServletContextListener {
   ------
} 

4. Register listeners with @ ServletComponentScan and @ WebListener

We can register Servlet listeners using @ ServletComponentScan and @ Configuration or @ SpringBootApplication annotations.

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 an embedded server. Find the listener example annotated with @ WebListener.

SessionCountListener.java

@WebListener
public class SessionCountListener implements HttpSessionListener {
   ------
} 

AdminInfoListener.java

@WebListener
public class AdminInfoListener implements ServletContextListener {
   ------
} 

Now use @ ServletComponentScan and @ SpringBootApplication in the main class, as shown below.

SpringBootAppStarter.java

@ServletComponentScan
@SpringBootApplication
public class SpringBootAppStarter {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootAppStarter.class, args);
    }
} 

5. Complete example: Listener + Filter + Servlet

Here we will provide a complete example of registering listeners, filters and servlets in Spring Boot.

We will use servletlistener registrationbean to register listeners, FilterRegistrationBean to register filters, and ServletRegistrationBean to register Servlets.

Find project structure.

Now find the complete code.

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.concretepage</groupId>
	<artifactId>spring-boot-app</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>
	<name>spring-boot-app</name>
	<description>Spring Boot Application</description>
	<parent>
	   <groupId>org.springframework.boot</groupId>
	   <artifactId>spring-boot-starter-parent</artifactId>
	   <version>2.0.3.RELEASE</version>
	   <relativePath/>
	</parent>
	<properties>
	   <java.version>9</java.version>
	</properties>
	<dependencies>
	   <dependency>
	      <groupId>org.springframework.boot</groupId>
	      <artifactId>spring-boot-starter-web</artifactId>
	   </dependency>	
           <dependency>
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-devtools</artifactId>
              <optional>true</optional>
           </dependency>
	</dependencies> 
	<build>
	   <plugins>
	      <plugin>
	  	 <groupId>org.springframework.boot</groupId>
	 	 <artifactId>spring-boot-maven-plugin</artifactId>
	      </plugin>
	   </plugins>
	</build>
</project>

SessionCountListener.java

package com.concretepage.listeners;
import java.util.concurrent.atomic.AtomicInteger;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

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

package com.concretepage.listeners;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

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.");			
	}
} 

ABCFilter.java

package com.concretepage.filters;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

public class ABCFilter implements Filter {
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	}
	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
		FilterChain chain) throws IOException, ServletException {
	    HttpServletRequest req = (HttpServletRequest) request;
	    System.out.println("Inside ABCFilter: "+ req.getRequestURI());
	    chain.doFilter(request, response);
	}
	@Override
	public void destroy() {
	}
} 

XYZFilter.java

package com.concretepage.filters;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

public class XYZFilter implements Filter {
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	}
	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
		  FilterChain chain) throws IOException, ServletException {
	     HttpServletRequest req = (HttpServletRequest) request;
	     System.out.println("Inside XYZFilter: "+ req.getRequestURI());
	     chain.doFilter(request, response);
	}
	@Override
	public void destroy() {
	}
} 

HelloCountryServlet.java

package com.concretepage.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HelloCountryServlet extends HttpServlet   {
	private static final long serialVersionUID = 1L;
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException{
	    doGet(request,response);
	}
        public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
   	    request.getSession();
	    out.println("<h3>Hello India!</h3>");	   	    
	    out.println("Admin: " + request.getServletContext().getAttribute("admin"));		    
	    out.println("<br/>Total Active Session: "+ request.getServletContext().getAttribute("activeSessions"));        
	}
} 

HelloStateServlet.java

package com.concretepage.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HelloStateServlet extends HttpServlet   {
	private static final long serialVersionUID = 1L;
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException{
	    doGet(request,response);
	}
        public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
            response.setContentType("text/html");
   	    request.getSession();
            PrintWriter out = response.getWriter();
	    out.println("<h3>Hello Uttar Pradesh!</h3>");	
	    out.println("Admin: " + request.getServletContext().getAttribute("admin"));	    
	    out.println("<br/>Total Active Session: "+ request.getServletContext().getAttribute("activeSessions"));           
	}
} 

WebConfig.java

package com.concretepage;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import com.concretepage.filters.ABCFilter;
import com.concretepage.filters.XYZFilter;
import com.concretepage.listeners.AdminInfoListener;
import com.concretepage.listeners.SessionCountListener;
import com.concretepage.servlets.HelloCountryServlet;
import com.concretepage.servlets.HelloStateServlet;

@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;
   }   
   //Register ABCFilter 	
   @Bean
   public FilterRegistrationBean<ABCFilter> abcFilter() {
	   FilterRegistrationBean<ABCFilter> filterRegBean = new FilterRegistrationBean<>();
	   filterRegBean.setFilter(new ABCFilter());
	   filterRegBean.addUrlPatterns("/app/*");
	   filterRegBean.setOrder(Ordered.LOWEST_PRECEDENCE -1);
	   return filterRegBean;
   }
   //Register XYZFilter   
   @Bean
   public FilterRegistrationBean<XYZFilter> xyzFilter() {
	   FilterRegistrationBean<XYZFilter> filterRegBean = new FilterRegistrationBean<>();
	   filterRegBean.setFilter(new XYZFilter());
	   filterRegBean.addUrlPatterns("/app/*");	
	   filterRegBean.setOrder(Ordered.LOWEST_PRECEDENCE -2);
	   return filterRegBean;
   }   
   
   //Register HelloCountryServlet   
   @Bean	
   public ServletRegistrationBean<HelloCountryServlet> countryServlet() {
	   ServletRegistrationBean<HelloCountryServlet> servRegBean = new ServletRegistrationBean<>();
	   servRegBean.setServlet(new HelloCountryServlet());
	   servRegBean.addUrlMappings("/app/country/*");
	   servRegBean.setLoadOnStartup(1);
	   return servRegBean;
   }
   //Register HelloStateServlet   
   @Bean	
   public ServletRegistrationBean<HelloStateServlet> stateServlet() {
	   ServletRegistrationBean<HelloStateServlet> servRegBean = new ServletRegistrationBean<>();
	   servRegBean.setServlet(new HelloStateServlet());
	   servRegBean.addUrlMappings("/app/state/*");
	   servRegBean.setLoadOnStartup(1);
	   return servRegBean;
   }   
} 

HelloWorldController.java

package com.concretepage.controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloWorldController {     
    @RequestMapping("/app/world")
    public String helloMsg(HttpServletRequest request) {
    	request.getSession();
    	String msg1 = "Admin: " + request.getServletContext().getAttribute("admin");    	
    	String msg2 = "Active Session Count: " + request.getServletContext().getAttribute("activeSessions");
        return msg1 + ", " + msg2;
    }
} 

SpringBootAppStarter.java

package com.concretepage;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringBootAppStarter {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootAppStarter.class, args);
    }
} 

6. Test program application

We can run our Spring Boot application in the following ways.

6.1 using Maven command

Download the source code of the project. Use the command prompt to go to the root folder of the project and run the command.

mvn spring-boot:run 

The Tomcat server will be started.

6.2 using Eclipse

Use the download link at the end of the article to download the source code of the project. Import the project into eclipse. Using the command prompt, go to the root folder of the project and run.

mvn clean eclipse:eclipse 

Then refresh the project in eclipse. Click Run as - > java application to run the main class SpringBootAppStarter. The Tomcat server will be started.

6.3 using executable jars

Using the command prompt, go to the root folder of the project and run the command.

mvn clean package

We will get the executable JAR spring-boot-app-0.0.1-SNAPSHOT.jar in the target folder. Run the JAR as follows

java -jar target/spring-boot-app-0.0.1-SNAPSHOT.jar 

The Tomcat server will be started.

Now we are ready to test the application. Run the following URL.

http://localhost:8080/app/country 

We will get the following output from the console.

output

Hello India!
Admin: Krishna
Total Active Session: 1 

reference

[1]Class ServletListenerRegistrationBean
[2]Spring Boot Reference Guide
[3]Spring Boot Servlet Mapping
[4]Spring Boot Filter
[5]Spring Boot Listener

Source download

[1]Register Listener with ServletListenerRegistrationBean
[2]Register Listener with @Component
[3]Register Listener with @ServletComponentScan and @WebListener

Posted by The Midnighter on Fri, 24 Sep 2021 00:44:56 -0700