Home  >  Spring Boot

Spring Boot Listener

By Arvind Rai, July 18, 2018
This page will walk through Spring Boot Listener example. We can 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.

Technologies Used

Find the technologies being used in our example.
1. Java 9
2. Spring 5.0.7.RELEASE
3. Spring Boot 2.0.3.RELEASE
4. Maven 3.5.2
5. Eclipse Oxygen

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 {
  ------
} 
AdminInfoListener.java
public class AdminInfoListener implements ServletContextListener {
   ------
} 
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;
   }   
   ------
} 

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 {
   ------
} 

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

Complete Example: Listener + Filter + Servlet

Here we will provide complete example to register listeners, filters and servlets in Spring Boot. We will use ServletListenerRegistrationBean to register listeners, FilterRegistrationBean to register filters and ServletRegistrationBean to register servlets.
Find the project structure.
Spring Boot Listener
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);
    }
} 

Test Application

We can run our Spring Boot application in following ways.
1. Using Maven Command: Download the project source code. Go to the root folder of the project using command prompt and run the command.
mvn spring-boot:run 
Tomcat server will be started.

2. Using Eclipse: Download the project source code using the download link given at the end of article. Import the project into eclipse. Using command prompt, go to the root folder of the project and run.
mvn clean eclipse:eclipse 
and then refresh the project in eclipse. Run Main class SpringBootAppStarter by clicking Run as -> Java Application. Tomcat server will be started.

3. Using Executable JAR: Using command prompt, go to the root folder of the project and run the command.
mvn clean package 
We will get executable JAR spring-boot-app-0.0.1-SNAPSHOT.jar in target folder. Run this JAR as
java -jar target/spring-boot-app-0.0.1-SNAPSHOT.jar 
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 following output in browser.
Output
Hello India!
Admin: Krishna
Total Active Session: 1 

References

Class ServletListenerRegistrationBean
Spring Boot Reference Guide
Spring Boot Servlet Mapping
Spring Boot Filter

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS


©2018 concretepage.com | Privacy Policy | Contact Us