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

相关文章

Java中流式并行操作parallelStream的原理和使用方法

《Java中流式并行操作parallelStream的原理和使用方法》本文详细介绍了Java中的并行流(parallelStream)的原理、正确使用方法以及在实际业务中的应用案例,并指出在使用并行流... 目录Java中流式并行操作parallelStream0. 问题的产生1. 什么是parallelS

Java中Redisson 的原理深度解析

《Java中Redisson的原理深度解析》Redisson是一个高性能的Redis客户端,它通过将Redis数据结构映射为Java对象和分布式对象,实现了在Java应用中方便地使用Redis,本文... 目录前言一、核心设计理念二、核心架构与通信层1. 基于 Netty 的异步非阻塞通信2. 编解码器三、

SpringBoot基于注解实现数据库字段回填的完整方案

《SpringBoot基于注解实现数据库字段回填的完整方案》这篇文章主要为大家详细介绍了SpringBoot如何基于注解实现数据库字段回填的相关方法,文中的示例代码讲解详细,感兴趣的小伙伴可以了解... 目录数据库表pom.XMLRelationFieldRelationFieldMapping基础的一些代

一篇文章彻底搞懂macOS如何决定java环境

《一篇文章彻底搞懂macOS如何决定java环境》MacOS作为一个功能强大的操作系统,为开发者提供了丰富的开发工具和框架,下面:本文主要介绍macOS如何决定java环境的相关资料,文中通过代码... 目录方法一:使用 which命令方法二:使用 Java_home工具(Apple 官方推荐)那问题来了,

Java HashMap的底层实现原理深度解析

《JavaHashMap的底层实现原理深度解析》HashMap基于数组+链表+红黑树结构,通过哈希算法和扩容机制优化性能,负载因子与树化阈值平衡效率,是Java开发必备的高效数据结构,本文给大家介绍... 目录一、概述:HashMap的宏观结构二、核心数据结构解析1. 数组(桶数组)2. 链表节点(Node

Java AOP面向切面编程的概念和实现方式

《JavaAOP面向切面编程的概念和实现方式》AOP是面向切面编程,通过动态代理将横切关注点(如日志、事务)与核心业务逻辑分离,提升代码复用性和可维护性,本文给大家介绍JavaAOP面向切面编程的概... 目录一、AOP 是什么?二、AOP 的核心概念与实现方式核心概念实现方式三、Spring AOP 的关

详解SpringBoot+Ehcache使用示例

《详解SpringBoot+Ehcache使用示例》本文介绍了SpringBoot中配置Ehcache、自定义get/set方式,并实际使用缓存的过程,文中通过示例代码介绍的非常详细,对大家的学习或者... 目录摘要概念内存与磁盘持久化存储:配置灵活性:编码示例引入依赖:配置ehcache.XML文件:配置

Java 虚拟线程的创建与使用深度解析

《Java虚拟线程的创建与使用深度解析》虚拟线程是Java19中以预览特性形式引入,Java21起正式发布的轻量级线程,本文给大家介绍Java虚拟线程的创建与使用,感兴趣的朋友一起看看吧... 目录一、虚拟线程简介1.1 什么是虚拟线程?1.2 为什么需要虚拟线程?二、虚拟线程与平台线程对比代码对比示例:三

vite搭建vue3项目的搭建步骤

《vite搭建vue3项目的搭建步骤》本文主要介绍了vite搭建vue3项目的搭建步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学... 目录1.确保Nodejs环境2.使用vite-cli工具3.进入项目安装依赖1.确保Nodejs环境

Python版本信息获取方法详解与实战

《Python版本信息获取方法详解与实战》在Python开发中,获取Python版本号是调试、兼容性检查和版本控制的重要基础操作,本文详细介绍了如何使用sys和platform模块获取Python的主... 目录1. python版本号获取基础2. 使用sys模块获取版本信息2.1 sys模块概述2.1.1