欢迎来到我的博客小站。  交流请加我微信好友: studyjava。  也欢迎关注公众号:Java学习之道 Fork me on GitHub

SpringBoot学习(八)-->SpringBoot之过滤器、监听器

本文将直接使用@WebFilter和@WebListener的方式,完成一个Filter 和一个 Listener。

过滤器(Filter)和 监听器(Listener)的注册方法和 Servlet 一样,不清楚的可以查看下这篇文章:【Spring Boot】 Servlet

SpringBoot之过滤器、监听器

1、工程预览:

先来一张maven结构工程图:

2、创建工程:

1)、创建一个maven项目,配置好pom.xml文件

 1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 2     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
 3     <modelVersion>4.0.0</modelVersion>
 4     <groupId>com.mmzs</groupId>
 5     <artifactId>springBoot04</artifactId>
 6     <packaging>war</packaging>
 7     <version>0.0.1-SNAPSHOT</version>
 8     <name>springBoot04 Maven Webapp</name>
 9     <url>http://maven.apache.org</url>
10 
11     <parent>
12         <groupId>org.springframework.boot</groupId>
13         <!-- 一定要有spring-boot-starter-parent,其中包含了spring的各种插件版本号 -->
14         <artifactId>spring-boot-starter-parent</artifactId>
15         <version>1.5.2.RELEASE</version>
16         <relativePath /><!-- lookup parent from repository -->
17     </parent>
18 
19     <!-- 父类统一管理版本信息 -->
20     <properties>
21         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
22         <!-- springboot 默认java版本是1.6,这里显示给它指定为1.8 -->
23         <java.version>1.7</java.version>
24     </properties>
25 
26     <dependencies>
27         <!-- 导入单元测试包 -->
28         <dependency>
29             <groupId>junit</groupId>
30             <artifactId>junit</artifactId>
31             <version>3.8.1</version>
32             <scope>test</scope>
33         </dependency>
34         
35         <!-- 导入spring boot的web支持,可以不写版本号,在spring-boot-starter-parent已经包含 -->
36         <dependency>
37             <groupId>org.springframework.boot</groupId>
38             <artifactId>spring-boot-starter-web</artifactId>
39         </dependency>
40     </dependencies>
41     <build>
42         <finalName>springBoot04</finalName>
43         <!-- 添加Spring boot的maven插件,可以不写版本号,在spring-boot-starter-parent已经包含  -->
44         <plugin>
45             <groupId>org.springframework.boot</groupId>
46             <artifactId>spring-boot-maven-plugin</artifactId>
47         </plugin>
48     </build>
49 </project>
pom.xml

2)、过滤器(Filter)文件

 1 /**
 2  * 
 3  */
 4 package com.mmzs.springboot.filter;
 5 
 6 import java.io.IOException;
 7 import javax.servlet.Filter;
 8 import javax.servlet.FilterChain;
 9 import javax.servlet.FilterConfig;
10 import javax.servlet.ServletException;
11 import javax.servlet.ServletRequest;
12 import javax.servlet.ServletResponse;
13 import javax.servlet.annotation.WebFilter;
14 
15 /**
16  * 使用注解标注过滤器
17  *
18  * @author: mmzs
19  * @date:   2018年4月23日 10:11:33
20  * @WebFilter将一个实现了javax.servlet.Filter接口的类定义为过滤器 属性filterName声明过滤器的名称, 可选
21  * 属性urlPatterns指定要过滤 的URL模式,也可使用属性value来声明.(指定要过滤的URL模式是必选属性)
22  * springboot注解详解:http://www.cnblogs.com/mmzs/p/8874349.html
23  * @version V1.0
24  */
25 @WebFilter(filterName = "myFilter", urlPatterns = "/*")
26 public class MyFilter implements Filter {
27 
28     @Override
29     public void destroy() {
30         System.out.println("过滤器销毁");
31     }
32 
33     @Override
34     public void doFilter(ServletRequest request, ServletResponse response,
35                          FilterChain chain) throws IOException, ServletException {
36         System.out.println("执行过滤操作");
37         chain.doFilter(request, response);
38         System.out.println("过滤执行之后的操作");
39     }
40 
41     @Override
42     public void init(FilterConfig config) throws ServletException {
43         System.out.println("过滤器初始化");
44     }
45 
46 }
MyFilter

3)、ServletContext监听器(Listener)文件

 1 /**
 2  * 
 3  */
 4 package com.mmzs.springboot.listener;
 5 
 6 import javax.servlet.ServletContextEvent;
 7 import javax.servlet.ServletContextListener;
 8 import javax.servlet.annotation.WebListener;
 9 
10 /**
11  * @author: mmzs
12  * @date:   2018年4月19日
13  * @Description: 使用@WebListener注解,实现ServletContextListener接口
14  * springboot注解详解:http://www.cnblogs.com/mmzs/p/8874349.html
15  * @version V1.0
16 */
17 @WebListener
18 public class MyServletContextListener implements ServletContextListener {
19 
20     @Override
21     public void contextInitialized(ServletContextEvent sce) {
22         System.out.println("ServletContex初始化");
23         System.out.println(sce.getServletContext().getServerInfo());
24     }
25 
26     @Override
27     public void contextDestroyed(ServletContextEvent sce) {
28         System.out.println("ServletContex销毁");
29     }
30 
31 }
MyServletContextListener

4)、HttpSession 监听器(Listener)文件

 1 /**
 2  * 
 3  */
 4 package com.mmzs.springboot.listener;
 5 
 6 import javax.servlet.annotation.WebListener;
 7 import javax.servlet.http.HttpSessionEvent;
 8 import javax.servlet.http.HttpSessionListener;
 9 
10 /**
11  * @author: mmzs
12  * @date:   2018年4月19日
13  * @Description: 监听Session的创建与销毁
14  * springboot注解详解:http://www.cnblogs.com/mmzs/p/8874349.html
15  * @version V1.0
16 */
17 @WebListener
18 public class MyHttpSessionListener implements HttpSessionListener {
19 
20     @Override
21     public void sessionCreated(HttpSessionEvent se) {
22         System.out.println("Session 被创建");
23     }
24 
25     @Override
26     public void sessionDestroyed(HttpSessionEvent se) {
27         System.out.println("Session 被销毁");
28     }
29 
30 }
MyHttpSessionListener

 5)、Controller

 1 package com.mmzs.springboot;
 2  
 3 import java.util.ArrayList;
 4 import java.util.HashMap;
 5 import java.util.List;
 6 import java.util.Map;
 7 
 8 import javax.servlet.http.HttpServletRequest;
 9 import javax.servlet.http.HttpSession;
10 
11 import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
12 import org.springframework.web.bind.annotation.RequestMapping;
13 import org.springframework.web.bind.annotation.RequestParam;
14 import org.springframework.web.bind.annotation.RestController;
15  
16 /**
17  * Created by mmzs 2018年4月2日 11:50:57
18  * springboot注解详解:http://www.cnblogs.com/mmzs/p/8874349.html
19  */
20 //用于标注控制层组件(如struts中的action),@ResponseBody和@Controller的合集,
21 //这样子获取的数据返回前台时也会自动转发为json格式。 
22 @RestController
23 //Spring Boot自动配置(auto-configuration):尝试根据你添加的jar依赖自动配置你的Spring应用。
24 @EnableAutoConfiguration
25 public class HelloController {
26  
27     @RequestMapping("/hello")
28     public String hello(HttpServletRequest request) {
29         HttpSession session = request.getSession();
30         return "Hello Spring-Boot";
31     }
32  
33 }
34  
HelloController

6)、启动入口类

 1 package com.mmzs.springboot;
 2 
 3 import org.springframework.boot.SpringApplication;
 4 import org.springframework.boot.autoconfigure.SpringBootApplication;
 5 import org.springframework.boot.web.servlet.ServletComponentScan;
 6 
 7 /**
 8  * 基于配置的servlet配置
 9  * Created by mmzs 2018年4月9日 11:43:59
10  */
11 @SpringBootApplication
12 //在 SpringBootApplication 上使用@ServletComponentScan 注解后,
13 //Servlet、Filter、Listener 可以直接通过 @WebServlet、@WebFilter、@WebListener 注解自动注册,无需其他代码
14 @ServletComponentScan
15 public class SpringBootSampleApplication {
16 
17     public static void main(String[] args) {
18         SpringApplication.run(SpringBootSampleApplication.class, args);
19     }
20 }
main

注意:不要忘记在 SpringBootSampleApplication.java 上添加 @ServletComponentScan注解。

3、访问测试:

1)、服务启动过程中会看到:

ServletContex初始化
Apache Tomcat/8.5.11
过滤器初始化

2)、服务启动后,随便访问一个页面会看到:

执行过滤操作
Session 被创建
过滤执行之后的操作

 4、小结

有人说没有“Session被创建”,因为你还没有用到session,在你访问的那个Controller中加入:

@RequestMapping
public String hello(HttpServletRequest request) {
    HttpSession session = request.getSession();
    return "Hello Spring-Boot";
}

至于如何使用代码的方式注册Filter和Listener,请参考这篇文章:【Spring Boot】 Servlet的介绍。不同的是需要使用 FilterRegistrationBean 和 ServletListenerRegistrationBean 这两个类。 

注意:

当你运行SpringBootSampleApplication的时候,spring boot只扫描当前包下及其子包下的注解,所以建议SpringBootSampleApplication放在需要扫描包的上一层或顶层。

5、参考文章

【Spring Boot 四】过滤器、监听器:https://www.27wy.cn/archives/362

该作者SpringBoot专题:点这里

 

posted @ 2018-07-05 11:09  淼淼之森  阅读(936)  评论(0编辑  收藏  举报
  👉转载请注明出处和署名