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中的路径变量示例详解

《SpringBoot中的路径变量示例详解》SpringBoot中PathVariable通过@PathVariable注解实现URL参数与方法参数绑定,支持多参数接收、类型转换、可选参数、默认值及... 目录一. 基本用法与参数映射1.路径定义2.参数绑定&nhttp://www.chinasem.cnbs

JAVA中安装多个JDK的方法

《JAVA中安装多个JDK的方法》文章介绍了在Windows系统上安装多个JDK版本的方法,包括下载、安装路径修改、环境变量配置(JAVA_HOME和Path),并说明如何通过调整JAVA_HOME在... 首先去oracle官网下载好两个版本不同的jdk(需要登录Oracle账号,没有可以免费注册)下载完

Spring StateMachine实现状态机使用示例详解

《SpringStateMachine实现状态机使用示例详解》本文介绍SpringStateMachine实现状态机的步骤,包括依赖导入、枚举定义、状态转移规则配置、上下文管理及服务调用示例,重点解... 目录什么是状态机使用示例什么是状态机状态机是计算机科学中的​​核心建模工具​​,用于描述对象在其生命

Spring Boot 结合 WxJava 实现文章上传微信公众号草稿箱与群发

《SpringBoot结合WxJava实现文章上传微信公众号草稿箱与群发》本文将详细介绍如何使用SpringBoot框架结合WxJava开发工具包,实现文章上传到微信公众号草稿箱以及群发功能,... 目录一、项目环境准备1.1 开发环境1.2 微信公众号准备二、Spring Boot 项目搭建2.1 创建

Java中Integer128陷阱

《Java中Integer128陷阱》本文主要介绍了Java中Integer与int的区别及装箱拆箱机制,重点指出-128至127范围内的Integer值会复用缓存对象,导致==比较结果为true,下... 目录一、Integer和int的联系1.1 Integer和int的区别1.2 Integer和in

SpringSecurity整合redission序列化问题小结(最新整理)

《SpringSecurity整合redission序列化问题小结(最新整理)》文章详解SpringSecurity整合Redisson时的序列化问题,指出需排除官方Jackson依赖,通过自定义反序... 目录1. 前言2. Redission配置2.1 RedissonProperties2.2 Red

IntelliJ IDEA2025创建SpringBoot项目的实现步骤

《IntelliJIDEA2025创建SpringBoot项目的实现步骤》本文主要介绍了IntelliJIDEA2025创建SpringBoot项目的实现步骤,文中通过示例代码介绍的非常详细,对大家... 目录一、创建 Spring Boot 项目1. 新建项目2. 基础配置3. 选择依赖4. 生成项目5.

JSONArray在Java中的应用操作实例

《JSONArray在Java中的应用操作实例》JSONArray是org.json库用于处理JSON数组的类,可将Java对象(Map/List)转换为JSON格式,提供增删改查等操作,适用于前后端... 目录1. jsONArray定义与功能1.1 JSONArray概念阐释1.1.1 什么是JSONA

Java JDK1.8 安装和环境配置教程详解

《JavaJDK1.8安装和环境配置教程详解》文章简要介绍了JDK1.8的安装流程,包括官网下载对应系统版本、安装时选择非系统盘路径、配置JAVA_HOME、CLASSPATH和Path环境变量,... 目录1.下载JDK2.安装JDK3.配置环境变量4.检验JDK官网下载地址:Java Downloads

Spring boot整合dubbo+zookeeper的详细过程

《Springboot整合dubbo+zookeeper的详细过程》本文讲解SpringBoot整合Dubbo与Zookeeper实现API、Provider、Consumer模式,包含依赖配置、... 目录Spring boot整合dubbo+zookeeper1.创建父工程2.父工程引入依赖3.创建ap