SpringBoot项目实战(7):Filter、Listener

2024-06-01 05:38

本文主要是介绍SpringBoot项目实战(7):Filter、Listener,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

  • 前言
  • 本文为了记录什么
  • 文中涉及的类基本以及作用
  • 基本代码
  • 实现过滤器
    • 通过代码注册
    • 通过注解实现Filter
  • 实现监听器
    • 通过代码注册
    • 通过注解实现监听器
  • 说在最后的话
  • 其他相关文章
  • 更多

前言

过滤器(Filter)是实现了javax.servlet.Filter接口的服务器端程序,主要的用途是过滤字符编码、做一些业务逻辑判断等。它是随web应用启动而启动的,只初始化一次,在web应用停止的时候才被销毁。
监听器(Listener)是实现了javax.servlet.ServletContextListener 接口的服务器端程序,它也是随web应用的启动而启动,只初始化一次,随web应用的停止而销毁。主要作用是: 做一些初始化的内容设置一些基本的内容,比如一些参数或者是一些固定的对象等。

springboot中使用过#滤#器(Filter)和监#听#器(Listener)有两种方式

第一种:代码注册(FilterRegistrationBeanServletListenerRegistrationBean

第二种:注解实现(SpringBootApplication上使用@ServletComponentScanFilterListener可以直接通过 @WebFilter@WebListener 注解自动注册。)

本文为了记录什么?

一:通过两种方式进行使用过滤器和监听器

二:了解过滤器的过滤规则和过滤优先级

文中涉及的类(基本)以及作用

一: WebAppFilter过滤 filter1和 filter2请求

二: WebAppForIndexFilter过滤 index请求

三:ServletController基本控制类,类中index 、filter1、filter2三种请求,命名空间为”/servlet”

四:WebAppListener监听器

基本代码

WebAppFilter

package com.zyd.servlet.config.filter;
import java.io.IOException;
import java.util.Date;
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;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;/*** @Description * @author zhangyd* @date 2017年4月7日 下午4:37:11 * @version V1.0* @since JDK : 1.7* @modify                 * @Review*/
public class WebAppFilter implements Filter {private static final Logger LOGGER = LoggerFactory.getLogger(WebAppFilter.class);@Overridepublic void destroy() {LOGGER.info("WebAppFilter - 过滤器已销毁...");}@Overridepublic void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)throws IOException, ServletException {HttpServletRequest request = (HttpServletRequest) arg0;LOGGER.info("WebAppFilter - Request URL: {}", request.getRequestURL().toString());LOGGER.info("WebAppFilter - Request port:{}", request.getServerPort());LOGGER.info("WebAppFilter - Request Method: {}", request.getMethod());HttpServletResponse response = (HttpServletResponse) arg1;response.setHeader("Current-Path", request.getServletPath());response.setHeader("My-Name", "MeiNanzi");arg2.doFilter(arg0, arg1);}@Overridepublic void init(FilterConfig arg0) throws ServletException {LOGGER.info("WebAppFilter - {}初始化过滤器...", new Date());}
}

WebAppForIndexFilter

package com.zyd.servlet.config.filter;
import java.io.IOException;
import java.util.Date;
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;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;/*** @Description * @author zhangyd* @date 2017年4月7日 下午4:37:11 * @version V1.0* @since JDK : 1.7* @modify                 * @Review*/
public class WebAppForIndexFilter implements Filter {private static final Logger LOGGER = LoggerFactory.getLogger(WebAppForIndexFilter.class);@Overridepublic void destroy() {LOGGER.info("WebAppForIndexFilter - 过滤器已销毁...");}@Overridepublic void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)throws IOException, ServletException {HttpServletRequest request = (HttpServletRequest) arg0;LOGGER.info("WebAppForIndexFilter - Request URL: {}", request.getRequestURL().toString());LOGGER.info("WebAppForIndexFilter - Request port:{}", request.getServerPort());LOGGER.info("WebAppForIndexFilter - Request Method: {}", request.getMethod());HttpServletResponse response = (HttpServletResponse) arg1;response.setHeader("Current-Path", request.getServletPath());response.setHeader("My-Name", "MeiNanzi");arg2.doFilter(arg0, arg1);}@Overridepublic void init(FilterConfig arg0) throws ServletException {LOGGER.info("WebAppForIndexFilter - {}初始化过滤器...", new Date());}
}

ServletController

package com.zyd.servlet.controller;
import java.util.Date;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/*** @Description * @author zhangyd* @date 2017年4月7日 下午4:37:11 * @version V1.0* @since JDK : 1.7* @modify                 * @Review*/
@RestController
@RequestMapping("/servlet")
public class ServletController {@RequestMapping("/index")public Object index() {return new Date() + " - index";}@RequestMapping("/filter1")public Object filter1() {return new Date() + " - filter1";}@RequestMapping("/filter2")public Object filter2() {return new Date() + " - filter2";}
}

WebAppListener

package com.zyd.servlet.config.listener;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class WebAppListener implements ServletContextListener {private static final Logger LOGGER = LoggerFactory.getLogger(WebAppListener.class); public static ServletContext context;@Overridepublic void contextDestroyed(ServletContextEvent arg0) {LOGGER.info("WebAppListener监听器已销毁...");}@Overridepublic void contextInitialized(ServletContextEvent arg0) {LOGGER.info("WebAppListener监听器开始初始化...");context = arg0.getServletContext();LOGGER.info("WebAppListener监听器初始化完成...");}
}

POM.xml 中需要的依赖

<!--支持 Web 应用开发,包含 Tomcat 和 spring-mvc -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope>
</dependency>

实现过滤器

通过代码注册

在Applaction启动类中添加以下代码

package com.zyd.servlet;
import java.util.ArrayList;
import java.util.List;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.annotation.Bean;
import com.zyd.servlet.config.filter.WebAppFilter;
import com.zyd.servlet.config.filter.WebAppForIndexFilter;
@SpringBootApplication
public class Applaction {/*** @Description 注册webAppFilter* @author zhangyd* @date 2017年4月7日 下午4:37:37 * @return*/@Beanpublic FilterRegistrationBean webAppFilterRegistrationBean() {FilterRegistrationBean registrationBean = new FilterRegistrationBean();registrationBean.setName("webAppFilter");WebAppFilter webAppFilter = new WebAppFilter();registrationBean.setFilter(webAppFilter);registrationBean.setOrder(0);List<String> urlList = new ArrayList<String>();urlList.add("/servlet/filter1");urlList.add("/servlet/filter2");registrationBean.setUrlPatterns(urlList);return registrationBean;}/*** @Description 注册webAppForIndexFilter* @author zhangyd* @date 2017年4月7日 下午4:37:37 * @return*/@Beanpublic FilterRegistrationBean webAppForIndexFilterRegistrationBean() {FilterRegistrationBean registrationBean = new FilterRegistrationBean();registrationBean.setName("webAppForIndexFilter");WebAppForIndexFilter webAppForIndexFilter = new WebAppForIndexFilter();registrationBean.setFilter(webAppForIndexFilter);registrationBean.setOrder(-1);List<String> urlList = new ArrayList<String>();urlList.add("/servlet/index");registrationBean.setUrlPatterns(urlList);return registrationBean;}public static void main(String[] args) {SpringApplication.run(Applaction.class, args);}
}

通过以上,即已经配置好了两个过滤器(webAppFilterwebAppForIndexFilter

启动并访问(xx/servlet/filter1xx/servlet/filter2xx/servlet/index),查看控制台打印内容

2017-04-07 16:43:38 [com.zyd.servlet.config.filter.WebAppFilter] INFO  - WebAppFilter - Request URL: http://127.0.0.1:8083/servlet/filter1
2017-04-07 16:43:38 [com.zyd.servlet.config.filter.WebAppFilter] INFO  - WebAppFilter - Request port:8083
2017-04-07 16:43:38 [com.zyd.servlet.config.filter.WebAppFilter] INFO  - WebAppFilter - Request Method: GET
2017-04-07 16:43:41 [com.zyd.servlet.config.filter.WebAppForIndexFilter] INFO  - WebAppForIndexFilter - Request URL: http://127.0.0.1:8083/servlet/index
2017-04-07 16:43:41 [com.zyd.servlet.config.filter.WebAppForIndexFilter] INFO  - WebAppForIndexFilter - Request port:8083
2017-04-07 16:43:41 [com.zyd.servlet.config.filter.WebAppForIndexFilter] INFO  - WebAppForIndexFilter - Request Method: GET
2017-04-07 16:43:44 [com.zyd.servlet.config.filter.WebAppFilter] INFO  - WebAppFilter - Request URL: http://127.0.0.1:8083/servlet/filter2
2017-04-07 16:43:44 [com.zyd.servlet.config.filter.WebAppFilter] INFO  - WebAppFilter - Request port:8083
2017-04-07 16:43:44 [com.zyd.servlet.config.filter.WebAppFilter] INFO  - WebAppFilter - Request Method: GET

可以看到WebAppFilter对应过滤filter1filter2请求,WebAppForIndexFilter对应过滤index请求

通过注解实现Filter

WebAppFilter修改为

// 添加这一段注解
@WebFilter(filterName = "WebAppFilter", urlPatterns = { "/servlet/filter1","/servlet/filter2" })
public class WebAppFilter implements Filter {...
}

WebAppForIndexFilter修改为

// 添加这一段注解
@WebFilter(filterName = "WebAppForIndexFilter", urlPatterns = { "/servlet/index" })
public class WebAppForIndexFilter implements Filter {...
}

Applaction修改为

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
// 添加下面这个注解
@ServletComponentScan
public class Applaction {public static void main(String[] args) {SpringApplication.run(Applaction.class, args);}
}

重新启动Applaction并访问(xx/servlet/filter1xx/servlet/filter2xx/servlet/index),查看控制台打印内容

2017-04-07 16:52:25 [com.zyd.servlet.config.filter.WebAppFilter] INFO  - WebAppFilter - Request URL: http://127.0.0.1:8083/servlet/filter2
2017-04-07 16:52:25 [com.zyd.servlet.config.filter.WebAppFilter] INFO  - WebAppFilter - Request port:8083
2017-04-07 16:52:25 [com.zyd.servlet.config.filter.WebAppFilter] INFO  - WebAppFilter - Request Method: GET
2017-04-07 16:52:29 [com.zyd.servlet.config.filter.WebAppForIndexFilter] INFO  - WebAppForIndexFilter - Request URL: http://127.0.0.1:8083/servlet/index
2017-04-07 16:52:29 [com.zyd.servlet.config.filter.WebAppForIndexFilter] INFO  - WebAppForIndexFilter - Request port:8083
2017-04-07 16:52:29 [com.zyd.servlet.config.filter.WebAppForIndexFilter] INFO  - WebAppForIndexFilter - Request Method: GET
2017-04-07 16:52:29 [com.zyd.servlet.config.filter.WebAppForIndexFilter] INFO  - WebAppForIndexFilter - Request URL: http://127.0.0.1:8083/servlet/index
2017-04-07 16:52:29 [com.zyd.servlet.config.filter.WebAppForIndexFilter] INFO  - WebAppForIndexFilter - Request port:8083
2017-04-07 16:52:29 [com.zyd.servlet.config.filter.WebAppForIndexFilter] INFO  - WebAppForIndexFilter - Request Method: GET
2017-04-07 16:52:33 [com.zyd.servlet.config.filter.WebAppFilter] INFO  - WebAppFilter - Request URL: http://127.0.0.1:8083/servlet/filter1
2017-04-07 16:52:33 [com.zyd.servlet.config.filter.WebAppFilter] INFO  - WebAppFilter - Request port:8083
2017-04-07 16:52:33 [com.zyd.servlet.config.filter.WebAppFilter] INFO  - WebAppFilter - Request Method: GET

到此为止就通过两种方式实现了Filter功能,这儿可以思考一个个问题

如果webAppFilter和webAppForIndexFilter都过滤了xx/servlet/filter2请求,具体实现是什么样的?谁在前谁在后?(吐槽:想不到什么业务场景会需要这种需求)可否手动控制过滤器的过滤顺序?

在webAppForIndexFilter中修改一下注解,让其也过滤filter2请求

@WebFilter(filterName = "WebAppForIndexFilter", urlPatterns = { "/servlet/index","/servlet/filter2" })

重启再次访问filter2

2017-04-07 17:00:32 [com.zyd.servlet.config.filter.WebAppFilter] INFO  - WebAppFilter - Request URL: http://127.0.0.1:8083/servlet/filter2
2017-04-07 17:00:32 [com.zyd.servlet.config.filter.WebAppFilter] INFO  - WebAppFilter - Request port:8083
2017-04-07 17:00:32 [com.zyd.servlet.config.filter.WebAppFilter] INFO  - WebAppFilter - Request Method: GET
2017-04-07 17:00:32 [com.zyd.servlet.config.filter.WebAppForIndexFilter] INFO  - WebAppForIndexFilter - Request URL: http://127.0.0.1:8083/servlet/filter2
2017-04-07 17:00:32 [com.zyd.servlet.config.filter.WebAppForIndexFilter] INFO  - WebAppForIndexFilter - Request port:8083
2017-04-07 17:00:32 [com.zyd.servlet.config.filter.WebAppForIndexFilter] INFO  - WebAppForIndexFilter - Request Method: GET

其实这种是默认的顺序,即两个类谁先被编译则谁在过滤顺序上就优先(不信的话可以把两个过滤器的名字改一下)

可以通过@Order进行控制过滤器的执行顺序

/** 定义执行的优先级,数字越低,优先级越高*/
@Order(-5)

实现监听器

通过代码注册

Applaction启动类中添加以下代码

package com.zyd.servlet;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.context.annotation.Bean;
import com.zyd.servlet.config.listener.WebAppListener;
@SpringBootApplication
public class Applaction {@Beanpublic ServletListenerRegistrationBean<WebAppListener> servletListenerRegistrationBean() {ServletListenerRegistrationBean<WebAppListener> servletListenerRegistrationBean = new ServletListenerRegistrationBean<WebAppListener>();servletListenerRegistrationBean.setListener(new WebAppListener());return servletListenerRegistrationBean;}public static void main(String[] args) {SpringApplication.run(Applaction.class, args);}
}

启动Applaction查看控制台信息

017-04-07 17:13:28 [org.springframework.boot.web.servlet.ServletRegistrationBean] INFO  - Mapping servlet: 'dispatcherServlet' to [/]
2017-04-07 17:13:28 [org.springframework.boot.web.servlet.AbstractFilterRegistrationBean] INFO  - Mapping filter: 'characterEncodingFilter' to: [/*]
2017-04-07 17:13:28 [org.springframework.boot.web.servlet.AbstractFilterRegistrationBean] INFO  - Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2017-04-07 17:13:28 [org.springframework.boot.web.servlet.AbstractFilterRegistrationBean] INFO  - Mapping filter: 'httpPutFormContentFilter' to: [/*]
2017-04-07 17:13:28 [org.springframework.boot.web.servlet.AbstractFilterRegistrationBean] INFO  - Mapping filter: 'requestContextFilter' to: [/*]
2017-04-07 17:13:28 [com.zyd.servlet.config.listener.WebAppListener] INFO  - WebAppListener监听器开始初始化...
2017-04-07 17:13:28 [com.zyd.servlet.config.listener.WebAppListener] INFO  - WebAppListener监听器初始化完成...
2017-04-07 17:13:28 [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter] INFO  - Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@32c57076: startup date [Fri Apr 07 17:13:24 CST 2017]; root of context hierarchy
2017-04-07 17:13:28 [org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry] INFO  - Mapped "{[/servlet/index]}" onto public java.lang.Object com.zyd.servlet.controller.ServletController.index()
2017-04-07 17:13:28 [org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry] INFO  - Mapped "{[/servlet/filter1]}" onto public java.lang.Object com.zyd.servlet.controller.ServletController.filter1()
2017-04-07 17:13:28 [org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry] INFO  - Mapped "{[/servlet/filter2]}" onto public java.lang.Object com.zyd.servlet.controller.ServletController.filter2()

通过注解实现监听器

方式和过滤器的实现方式基本一致,在Applaction启动类中添加@ServletComponentScan注解,并且在WebAppListener类中添加@WebListener注解

到此就完成了监听器和过滤器的两种实现方式。

说在最后的话

如有不对的地方或者需要补充的地方,欢迎留言告知。

感谢生命中遇到的每一个人,感谢每一个给自己压力的人,感谢每一个恨自己的人

Git源码

码云源码

其他相关文章

SpringBoot项目实战(7):过滤器、监听器
SpringBoot项目实战(6):整合Log4j和Aop,实现简单的日志记录
SpringBoot项目实战(5):集成分页插件
SpringBoot项目实战(4):集成Mybatis
SpringBoot项目实战(3):整合Freemark模板
SpringBoot项目实战(2):集成SpringBoot
SpringBoot项目实战(1):新建Maven项目

更多

敬请访问…

这篇关于SpringBoot项目实战(7):Filter、Listener的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1020126

相关文章

Spring Boot中WebSocket常用使用方法详解

《SpringBoot中WebSocket常用使用方法详解》本文从WebSocket的基础概念出发,详细介绍了SpringBoot集成WebSocket的步骤,并重点讲解了常用的使用方法,包括简单消... 目录一、WebSocket基础概念1.1 什么是WebSocket1.2 WebSocket与HTTP

SpringBoot+Docker+Graylog 如何让错误自动报警

《SpringBoot+Docker+Graylog如何让错误自动报警》SpringBoot默认使用SLF4J与Logback,支持多日志级别和配置方式,可输出到控制台、文件及远程服务器,集成ELK... 目录01 Spring Boot 默认日志框架解析02 Spring Boot 日志级别详解03 Sp

java中反射Reflection的4个作用详解

《java中反射Reflection的4个作用详解》反射Reflection是Java等编程语言中的一个重要特性,它允许程序在运行时进行自我检查和对内部成员(如字段、方法、类等)的操作,本文将详细介绍... 目录作用1、在运行时判断任意一个对象所属的类作用2、在运行时构造任意一个类的对象作用3、在运行时判断

java如何解压zip压缩包

《java如何解压zip压缩包》:本文主要介绍java如何解压zip压缩包问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录Java解压zip压缩包实例代码结果如下总结java解压zip压缩包坐在旁边的小伙伴问我怎么用 java 将服务器上的压缩文件解压出来,

SpringBoot中SM2公钥加密、私钥解密的实现示例详解

《SpringBoot中SM2公钥加密、私钥解密的实现示例详解》本文介绍了如何在SpringBoot项目中实现SM2公钥加密和私钥解密的功能,通过使用Hutool库和BouncyCastle依赖,简化... 目录一、前言1、加密信息(示例)2、加密结果(示例)二、实现代码1、yml文件配置2、创建SM2工具

Spring WebFlux 与 WebClient 使用指南及最佳实践

《SpringWebFlux与WebClient使用指南及最佳实践》WebClient是SpringWebFlux模块提供的非阻塞、响应式HTTP客户端,基于ProjectReactor实现,... 目录Spring WebFlux 与 WebClient 使用指南1. WebClient 概述2. 核心依

Spring Boot @RestControllerAdvice全局异常处理最佳实践

《SpringBoot@RestControllerAdvice全局异常处理最佳实践》本文详解SpringBoot中通过@RestControllerAdvice实现全局异常处理,强调代码复用、统... 目录前言一、为什么要使用全局异常处理?二、核心注解解析1. @RestControllerAdvice2

Spring IoC 容器的使用详解(最新整理)

《SpringIoC容器的使用详解(最新整理)》文章介绍了Spring框架中的应用分层思想与IoC容器原理,通过分层解耦业务逻辑、数据访问等模块,IoC容器利用@Component注解管理Bean... 目录1. 应用分层2. IoC 的介绍3. IoC 容器的使用3.1. bean 的存储3.2. 方法注

Spring事务传播机制最佳实践

《Spring事务传播机制最佳实践》Spring的事务传播机制为我们提供了优雅的解决方案,本文将带您深入理解这一机制,掌握不同场景下的最佳实践,感兴趣的朋友一起看看吧... 目录1. 什么是事务传播行为2. Spring支持的七种事务传播行为2.1 REQUIRED(默认)2.2 SUPPORTS2

怎样通过分析GC日志来定位Java进程的内存问题

《怎样通过分析GC日志来定位Java进程的内存问题》:本文主要介绍怎样通过分析GC日志来定位Java进程的内存问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、GC 日志基础配置1. 启用详细 GC 日志2. 不同收集器的日志格式二、关键指标与分析维度1.