快捷搜索:  汽车  科技

springboot数据拦截器(Springboot项目实战六)

springboot数据拦截器(Springboot项目实战六)测试过滤器效果两种方式使过滤器生效本文共分x部分:项目结构编写WebAppAllFilter和WebAppForIndexFilter

springboot数据拦截器(Springboot项目实战六)(1)

两种方式实现过滤器、监听器

序言

本文主要记录Springboot实现过滤器、监听器的两种方式

  1. SpringBean的方式注册(FilterRegistrationBean 和 ServletListenerRegistrationBean)

  2. 通过@WebFilter、@WebListener 注解实现(需要在Applaction中配置@ServletComponentScan注解)

本文共分x部分:

  1. 项目结构

  2. 编写WebAppAllFilter和WebAppForIndexFilter

  3. 两种方式使过滤器生效

  4. 测试过滤器效果

  5. 编写WebAppListener和WebAppListener2

  6. 两种方式使监听器生效

  7. 测试监听器

  8. 其他内容

友情提示:请参考同类文章

Springboot项目实战(一):Idea构建Springboot项目并整合Freemarker

Springboot项目实战(二):集成mybatis和分页插件

Springboot项目实战(三):集成Logback进行简单的日志记录

二、编写WebAppAllFilter.java和WebAppForIndexFilter.java

springboot数据拦截器(Springboot项目实战六)(2)

WebAppAllFilter

springboot数据拦截器(Springboot项目实战六)(3)

WebAppForIndexFilter

三、两种方式使过滤器生效

第一种:即WebAppAllFilter中的WebFilter注解

@WebFilter(filterName = "WebAppAllFilter" urlPatterns = { "/*" })

表示拦截所有请求

第二种:通过Springbean注入

springboot数据拦截器(Springboot项目实战六)(4)

SpringBean

setUrlPatterns接收的为一个List参数,表示要过滤的请求路径,源码:

springboot数据拦截器(Springboot项目实战六)(5)

setUrlPatterns

四、测试过滤器效果

编写一个简单的Controller,实现三种不同的请求路径,方便测试两种过滤器的效果

springboot数据拦截器(Springboot项目实战六)(6)

Controller

运行项目,分别访问下面三个路径,预期的结果为访问index时会打印出WebAppAllFilter和WebAppForIndexFilter中的日志,访问filter1和filter2应该只会打印出WebAppAllFilter中的日志。

http://localhost:8080/servlet/index

http://localhost:8080/servlet/filter1

http://localhost:8080/servlet/filter2

开始试验:

springboot数据拦截器(Springboot项目实战六)(7)

测试过滤器

结果与猜想一致!过滤器添加成功!

五、编写WebAppListener.java和WebAppListener2.java

监听器和过滤器的实现方式基本一样

springboot数据拦截器(Springboot项目实战六)(8)

WebAppListener

springboot数据拦截器(Springboot项目实战六)(9)

WebAppListener2

六、两种方式使监听器生效

第一种:即WebAppListener中的WebListener注解

第二种:通过SpringBean注入

springboot数据拦截器(Springboot项目实战六)(10)

SpringBean注入监听器

七、测试监听器

启动程序,查看监听器是否执行

springboot数据拦截器(Springboot项目实战六)(11)

八、其他内容

感谢各位的关注。如有问题,欢迎指正;如有建议,请多指教。

最后附上源代码:https://github.com/zhangyd-c/springboot/tree/master/springboot-servlet

我就是我,不一样的烟火。

猜您喜欢: