Spring Boot监听器Listener介绍

x33g5p2x  于2022-09-23 转载在 Spring  
字(13.5k)|赞(0)|评价(0)|浏览(351)

本文将介绍 Spring Boot Listener 示例。我们可以使用 ServletListenerRegistrationBean@Component@ServletComponentScan 在 Spring Boot 中注册 servlet 监听器。 ServletListenerRegistrationBean 类将 servlet 监听器注册为 Spring bean。 @ServletComponentScan 注释扫描使用 @WebListener 注释的 servlet 监听器,它仅在使用嵌入式服务器时有效。在我们的示例中,我们将使用 HttpSessionListenerServletContextListener 创建监听器,并提供完整的示例以在 Spring Boot 中注册它们。

使用的技术

使用的技术

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

使用 ServletListenerRegistrationBean 注册监听器

ServletListenerRegistrationBean 将 servlet 监听器注册为 Spring bean。 ServletListenerRegistrationBean 提供了 setListener() 方法来分配监听器。假设我们有如下听众。
SessionCountListener.java

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

AdminInfoListener.java

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

现在在 JavaConfig 中,我们将使用 ServletListenerRegistrationBean 类将我们的监听器注册为 Spring bean。 WebConfig.java

@Configuration
public class WebConfig {
   //Register SessionCountListener	
   @Bean
   public ServletListenerRegistrationBean&ltSessionCountListener> sessionCountListener() {
	   ServletListenerRegistrationBean&ltSessionCountListener> listenerRegBean = new ServletListenerRegistrationBean<>();
	   listenerRegBean.setListener(new SessionCountListener());
	   return listenerRegBean;
   }
   //Register AdminInfoListener	
   @Bean
   public ServletListenerRegistrationBean&ltAdminInfoListener> adminInfoListener() {
	   ServletListenerRegistrationBean&ltAdminInfoListener> listenerRegBean = new ServletListenerRegistrationBean<>();
	   listenerRegBean.setListener(new AdminInfoListener());
	   return listenerRegBean;
   }   
   ------
}

使用@Component 注册监听器

我们可以通过使用 Spring @Component 注释它来在 Spring Boot 中注册 servlet 监听器,如下所示。
SessionCountListener.java

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

AdminInfoListener.java

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

使用@ServletComponentScan 和@WebListener 注册监听器

我们可以使用带有 @Configuration@SpringBootApplication 注释的 @ServletComponentScan 注册 servlet 监听器。使用 @WebListener 注释的 servlet 监听器将被 @ServletComponentScan 扫描。它还扫描分别用 @WebServlet@WebFilter 注释的 servlet 和过滤器。 @ServletComponentScan 仅在使用嵌入式服务器时有效。查找带有 @WebListener 注释的示例监听器。
SessionCountListener.java

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

AdminInfoListener.java

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

现在在 Main 类中使用 @ServletComponentScan@SpringBootApplication,如下所示。
SpringBootAppStarter.java

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

完整示例:Listener + Filter + Servlet

在这里,我们将提供完整的示例来在 Spring Boot 中注册监听器、过滤器和 servlet。我们将使用 ServletListenerRegistrationBean 注册监听器,使用 FilterRegistrationBean 注册过滤器,使用 ServletRegistrationBean 注册 servlet。
找到项目结构。

现在找到完整的代码。
pom.xml

<?xml version="1.0" encoding="UTF-8"?>
&ltproject 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">
	
	&ltmodelVersion&gt4.0.0</modelVersion>
	&ltgroupId&gtcom.concretepage</groupId>
	&ltartifactId&gtspring-boot-app</artifactId>
	&ltversion&gt0.0.1-SNAPSHOT</version>
	&ltpackaging&gtjar</packaging>
	&ltname&gtspring-boot-app</name>
	&ltdescription&gtSpring Boot Application</description>
	&ltparent>
	   &ltgroupId&gtorg.springframework.boot</groupId>
	   &ltartifactId&gtspring-boot-starter-parent</artifactId>
	   &ltversion&gt2.0.3.RELEASE</version>
	   &ltrelativePath/>
	</parent>
	&ltproperties>
	   &ltjava.version&gt9</java.version>
	</properties>
	&ltdependencies>
	   &ltdependency>
	      &ltgroupId&gtorg.springframework.boot</groupId>
	      &ltartifactId&gtspring-boot-starter-web</artifactId>
	   </dependency>	
           &ltdependency>
              &ltgroupId&gtorg.springframework.boot</groupId>
              &ltartifactId&gtspring-boot-devtools</artifactId>
              &ltoptional&gttrue</optional>
           </dependency>
	</dependencies> 
	&ltbuild>
	   &ltplugins>
	      &ltplugin>
	  	 &ltgroupId&gtorg.springframework.boot</groupId>
	 	 &ltartifactId&gtspring-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("&lth3&gtHello India!</h3>");	   	    
	    out.println("Admin: " + request.getServletContext().getAttribute("admin"));		    
	    out.println("&ltbr/&gtTotal 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("&lth3&gtHello Uttar Pradesh!</h3>");	
	    out.println("Admin: " + request.getServletContext().getAttribute("admin"));	    
	    out.println("&ltbr/&gtTotal 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&ltSessionCountListener> sessionCountListener() {
	   ServletListenerRegistrationBean&ltSessionCountListener> listenerRegBean = new ServletListenerRegistrationBean<>();
	   listenerRegBean.setListener(new SessionCountListener());
	   return listenerRegBean;
   }
   //Register AdminInfoListener	
   @Bean
   public ServletListenerRegistrationBean&ltAdminInfoListener> adminInfoListener() {
	   ServletListenerRegistrationBean&ltAdminInfoListener> listenerRegBean = new ServletListenerRegistrationBean<>();
	   listenerRegBean.setListener(new AdminInfoListener());
	   return listenerRegBean;
   }   
   //Register ABCFilter 	
   @Bean
   public FilterRegistrationBean&ltABCFilter> abcFilter() {
	   FilterRegistrationBean&ltABCFilter> filterRegBean = new FilterRegistrationBean<>();
	   filterRegBean.setFilter(new ABCFilter());
	   filterRegBean.addUrlPatterns("/app/*");
	   filterRegBean.setOrder(Ordered.LOWEST_PRECEDENCE -1);
	   return filterRegBean;
   }
   //Register XYZFilter   
   @Bean
   public FilterRegistrationBean&ltXYZFilter> xyzFilter() {
	   FilterRegistrationBean&ltXYZFilter> filterRegBean = new FilterRegistrationBean<>();
	   filterRegBean.setFilter(new XYZFilter());
	   filterRegBean.addUrlPatterns("/app/*");	
	   filterRegBean.setOrder(Ordered.LOWEST_PRECEDENCE -2);
	   return filterRegBean;
   }   
   
   //Register HelloCountryServlet   
   @Bean	
   public ServletRegistrationBean&ltHelloCountryServlet> countryServlet() {
	   ServletRegistrationBean&ltHelloCountryServlet> servRegBean = new ServletRegistrationBean<>();
	   servRegBean.setServlet(new HelloCountryServlet());
	   servRegBean.addUrlMappings("/app/country/*");
	   servRegBean.setLoadOnStartup(1);
	   return servRegBean;
   }
   //Register HelloStateServlet   
   @Bean	
   public ServletRegistrationBean&ltHelloStateServlet> stateServlet() {
	   ServletRegistrationBean&ltHelloStateServlet> 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);
    }
}

测试应用

我们可以通过以下方式运行我们的 Spring Boot 应用程序。
1。使用 Maven 命令:下载项目源代码。使用命令提示符转到项目的根文件夹并运行命令。

mvn spring-boot:run

Tomcat 服务器将被启动。

2。使用 Eclipse:使用文章末尾给出的下载链接下载项目源代码。将项目导入eclipse。使用命令提示符,转到项目的根文件夹并运行。

mvn clean eclipse:eclipse

然后在eclipse中刷新项目。通过单击 Run as -> Java Application 运行主类 SpringBootAppStarter。 Tomcat 服务器将被启动。

3。使用 Executable JAR:使用命令提示符,转到项目的根文件夹并运行命令。

mvn clean package

我们将在目标文件夹中获得可执行的 JAR spring-boot-app-0.0.1-SNAPSHOT.jar。将此 JAR 运行为

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

Tomcat 服务器将被启动。

现在我们准备好测试应用程序了。运行以下 URL。

http://localhost:8080/app/country

我们将在浏览器中得到以下输出。
输出

Hello India!
Admin: Krishna
Total Active Session: 1

参考

Class ServletListenerRegistrationBean
Spring Boot Reference Guide

相关文章