SpringBoot学习(八)-->SpringBoot之过滤器、监听器
本文将直接使用@WebFilter和@WebListener的方式,完成一个Filter 和一个 Listener。
过滤器(Filter)和 监听器(Listener)的注册方法和 Servlet 一样,不清楚的可以查看下这篇文章:【Spring Boot】 Servlet
SpringBoot之过滤器、监听器
1、工程预览:
先来一张maven结构工程图:

2、创建工程:
1)、创建一个maven项目,配置好pom.xml文件
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mmzs</groupId>
<artifactId>springBoot04</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>springBoot04 Maven Webapp</name>
<url>http://maven.apache.org</url> <parent>
<groupId>org.springframework.boot</groupId>
<!-- 一定要有spring-boot-starter-parent,其中包含了spring的各种插件版本号 -->
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
<relativePath /><!-- lookup parent from repository -->
</parent> <!-- 父类统一管理版本信息 -->
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- springboot 默认java版本是1.6,这里显示给它指定为1.8 -->
<java.version>1.7</java.version>
</properties> <dependencies>
<!-- 导入单元测试包 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency> <!-- 导入spring boot的web支持,可以不写版本号,在spring-boot-starter-parent已经包含 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<build>
<finalName>springBoot04</finalName>
<!-- 添加Spring boot的maven插件,可以不写版本号,在spring-boot-starter-parent已经包含 -->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</build>
</project>
pom.xml
2)、过滤器(Filter)文件
/**
*
*/
package com.mmzs.springboot.filter; 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.annotation.WebFilter; /**
* 使用注解标注过滤器
*
* @author: mmzs
* @date: 2018年4月23日 10:11:33
* @WebFilter将一个实现了javax.servlet.Filter接口的类定义为过滤器 属性filterName声明过滤器的名称, 可选
* 属性urlPatterns指定要过滤 的URL模式,也可使用属性value来声明.(指定要过滤的URL模式是必选属性)
* springboot注解详解:http://www.cnblogs.com/mmzs/p/8874349.html
* @version V1.0
*/
@WebFilter(filterName = "myFilter", urlPatterns = "/*")
public class MyFilter implements Filter { @Override
public void destroy() {
System.out.println("过滤器销毁");
} @Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
System.out.println("执行过滤操作");
chain.doFilter(request, response);
System.out.println("过滤执行之后的操作");
} @Override
public void init(FilterConfig config) throws ServletException {
System.out.println("过滤器初始化");
} }
MyFilter
3)、ServletContext监听器(Listener)文件
/**
*
*/
package com.mmzs.springboot.listener; import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener; /**
* @author: mmzs
* @date: 2018年4月19日
* @Description: 使用@WebListener注解,实现ServletContextListener接口
* springboot注解详解:http://www.cnblogs.com/mmzs/p/8874349.html
* @version V1.0
*/
@WebListener
public class MyServletContextListener implements ServletContextListener { @Override
public void contextInitialized(ServletContextEvent sce) {
System.out.println("ServletContex初始化");
System.out.println(sce.getServletContext().getServerInfo());
} @Override
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("ServletContex销毁");
} }
MyServletContextListener
4)、HttpSession 监听器(Listener)文件
/**
*
*/
package com.mmzs.springboot.listener; import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener; /**
* @author: mmzs
* @date: 2018年4月19日
* @Description: 监听Session的创建与销毁
* springboot注解详解:http://www.cnblogs.com/mmzs/p/8874349.html
* @version V1.0
*/
@WebListener
public class MyHttpSessionListener implements HttpSessionListener { @Override
public void sessionCreated(HttpSessionEvent se) {
System.out.println("Session 被创建");
} @Override
public void sessionDestroyed(HttpSessionEvent se) {
System.out.println("Session 被销毁");
} }
MyHttpSessionListener
5)、Controller
package com.mmzs.springboot; import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession; import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; /**
* Created by mmzs 2018年4月2日 11:50:57
* springboot注解详解:http://www.cnblogs.com/mmzs/p/8874349.html
*/
//用于标注控制层组件(如struts中的action),@ResponseBody和@Controller的合集,
//这样子获取的数据返回前台时也会自动转发为json格式。
@RestController
//Spring Boot自动配置(auto-configuration):尝试根据你添加的jar依赖自动配置你的Spring应用。
@EnableAutoConfiguration
public class HelloController { @RequestMapping("/hello")
public String hello(HttpServletRequest request) {
HttpSession session = request.getSession();
return "Hello Spring-Boot";
} }
HelloController
6)、启动入口类
package com.mmzs.springboot; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan; /**
* 基于配置的servlet配置
* Created by mmzs 2018年4月9日 11:43:59
*/
@SpringBootApplication
//在 SpringBootApplication 上使用@ServletComponentScan 注解后,
//Servlet、Filter、Listener 可以直接通过 @WebServlet、@WebFilter、@WebListener 注解自动注册,无需其他代码
@ServletComponentScan
public class SpringBootSampleApplication { public static void main(String[] args) {
SpringApplication.run(SpringBootSampleApplication.class, args);
}
}
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专题:点这里
SpringBoot学习(八)-->SpringBoot之过滤器、监听器的更多相关文章
- Spring boot 学习八 Springboot的filter
一: 传统的javaEE增加Filter是在web.xml中配置,如以下代码: <filter> <filter-name>TestFilter</filter-nam ...
- SpringBoot学习之SpringBoot执行器
在以往的分布式开发当中,各个服务节点的监控必不可少.监控包含有很多方面,比如说:内存占用情况,节点是否健康等.在spring-boot会给我们提供相关资源监控叫做spring-boot-actuato ...
- SpringBoot学习(七)-->SpringBoot在web开发中的配置
SpringBoot在web开发中的配置 Web开发的自动配置类:在Maven Dependencies-->spring-boot-1.5.2.RELEASE.jar-->org.spr ...
- SpringBoot学习(六)-->SpringBoot的自动配置的原理
Spring Boot的自动配置的原理 Spring Boot在进行SpringApplication对象实例化时会加载META-INF/spring.factories文件,将该配置文件中的配置载入 ...
- SpringBoot学习(五)-->SpringBoot的核心
SpringBoot的核心 1.入口类和@SpringBootApplication Spring Boot的项目一般都会有*Application的入口类,入口类中会有main方法,这是一个标准的J ...
- SpringBoot学习(四)-->SpringBoot快速入门,开山篇
Spring Boot简介 Spring Boot的目的在于创建和启动新的基于Spring框架的项目.Spring Boot会选择最适合的Spring子项目和第三方开源库进行整合.大部分Spring ...
- SpringBoot学习<二>——SpringBoot的默认配置文件application和多环境配置
一.SpringBoot的默认文件appliction 上一篇文章已经说明,springboot启动会内嵌tomcat,端口也是默认的8080,如果我们想要改变端口如果做呢? 在springboot项 ...
- SpringBoot学习(一):SpringBoot入门
1.Spring Boot 简介 1) 简化Spring应用开发的一个框架: 2) 整个Spring技术栈的一个大整合: 3) J2EE开发的一站式解决方案: 2.微服务 2014,martin fo ...
- SpringBoot学习- 5、整合Redis
SpringBoot学习足迹 SpringBoot项目中访问Redis主要有两种方式:JedisPool和RedisTemplate,本文使用JedisPool 1.pom.xml添加dependen ...
随机推荐
- spring BeanPostProcessor
BeanPostProcessor spring使用BeanPostProcessor接口来处理生命周期的回调 BeanPostProcessor接口定义的两个方法,分别在bean的(实例化配置和初始 ...
- python之路(七)-递归算法
递归 特点 递归算法是一种直接或者间接地调用自身算法的过程.在计算机编写程序中,递归算法对解决一大类问题是十分有效的,它往往使算法的描述简洁而且易于理解. 递归算法解决问题的特点: (1) 递归就是在 ...
- ModelAndView返回json对象的方法
这是在spring4之后. @RequestMapping(value = "/returnjson") public ModelAndView getfsd(){ ModelAn ...
- UML顺序图知识点介绍(Sequence Diagram)
消息 调用消息 调用(procedure call)消息的发送者把控制传递给消息的接收者,然后停止活动,等待消息接受者放弃会返回控制 在Rational Rose(2016版本如图所示) 异步消息 异 ...
- Drools为什么没有规则流Flow Flie
哪个大神能告诉我,我安装的是Drools7.7.0,为什么没有网上说的flow file啊?怎么才能出来规则流呢? 上图是我本地的显示,下图是网上的图片.
- L'opzione di luce del puntatore laser
Prima di tutto, sono di buone dimensioni, non i 'mini' puntatori laser che altri stanno vendendo. È ...
- ubuntu 16.04 安装 ssh
只要一条命令: sudo apt-get install openssh-server
- Jenkins pipeline 并行执行任务流
笔者在<Jenkins 在声明式 pipeline 中并行执行任务>一文中介绍了如何在声明式 pipeline 中执行并行的任务.前一段时间,Jenkins 发布了 1.3 版的声明式 p ...
- Android P正式版即将到来:后台应用保活、消息推送的真正噩梦
1.前言 对于广大Android开发者来说,Android O(即Android 8.0)还没玩热,Andriod P(即Andriod 9.0)又要来了. 下图上谷歌官方公布的Android P ...
- 移动web-bootstrap
1bootstarp布局容器+栅格系统的使用 1.101-移动web-bootstrap中的布局容器 1.container和container-fluid的区别? a) container ...