本文将介绍 Spring Boot Listener 示例。我们可以使用 ServletListenerRegistrationBean
或 @Component
或 @ServletComponentScan
在 Spring Boot 中注册 servlet 监听器。 ServletListenerRegistrationBean
类将 servlet 监听器注册为 Spring bean。 @ServletComponentScan
注释扫描使用 @WebListener
注释的 servlet 监听器,它仅在使用嵌入式服务器时有效。在我们的示例中,我们将使用 HttpSessionListener
和 ServletContextListener
创建监听器,并提供完整的示例以在 Spring Boot 中注册它们。
使用的技术
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<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;
}
------
}
我们可以通过使用 Spring @Component
注释它来在 Spring Boot 中注册 servlet 监听器,如下所示。
SessionCountListener.java
@Component
public class SessionCountListener implements HttpSessionListener {
------
}
AdminInfoListener.java
@Component
public class AdminInfoListener implements ServletContextListener {
------
}
我们可以使用带有 @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);
}
}
在这里,我们将提供完整的示例来在 Spring Boot 中注册监听器、过滤器和 servlet。我们将使用 ServletListenerRegistrationBean
注册监听器,使用 FilterRegistrationBean
注册过滤器,使用 ServletRegistrationBean
注册 servlet。
找到项目结构。
现在找到完整的代码。
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);
}
}
我们可以通过以下方式运行我们的 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
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://www.concretepage.com/spring-boot/spring-boot-listener
内容来源于网络,如有侵权,请联系作者删除!