springboot数据拦截器(Springboot项目实战六)
springboot数据拦截器(Springboot项目实战六)测试过滤器效果两种方式使过滤器生效本文共分x部分:项目结构编写WebAppAllFilter和WebAppForIndexFilter
两种方式实现过滤器、监听器
序言本文主要记录Springboot实现过滤器、监听器的两种方式
-
SpringBean的方式注册(FilterRegistrationBean 和 ServletListenerRegistrationBean)
-
通过@WebFilter、@WebListener 注解实现(需要在Applaction中配置@ServletComponentScan注解)
本文共分x部分:
-
项目结构
-
编写WebAppAllFilter和WebAppForIndexFilter
-
两种方式使过滤器生效
-
测试过滤器效果
-
编写WebAppListener和WebAppListener2
-
两种方式使监听器生效
-
测试监听器
-
其他内容
友情提示:请参考同类文章
Springboot项目实战(一):Idea构建Springboot项目并整合Freemarker
Springboot项目实战(二):集成mybatis和分页插件
Springboot项目实战(三):集成Logback进行简单的日志记录
WebAppAllFilter
WebAppForIndexFilter
三、两种方式使过滤器生效第一种:即WebAppAllFilter中的WebFilter注解
@WebFilter(filterName = "WebAppAllFilter" urlPatterns = { "/*" })
表示拦截所有请求
第二种:通过Springbean注入
SpringBean
setUrlPatterns接收的为一个List参数,表示要过滤的请求路径,源码:
setUrlPatterns
四、测试过滤器效果编写一个简单的Controller,实现三种不同的请求路径,方便测试两种过滤器的效果
Controller
运行项目,分别访问下面三个路径,预期的结果为访问index时会打印出WebAppAllFilter和WebAppForIndexFilter中的日志,访问filter1和filter2应该只会打印出WebAppAllFilter中的日志。
http://localhost:8080/servlet/index
http://localhost:8080/servlet/filter1
http://localhost:8080/servlet/filter2
开始试验:
测试过滤器
结果与猜想一致!过滤器添加成功!
监听器和过滤器的实现方式基本一样
WebAppListener
WebAppListener2
六、两种方式使监听器生效第一种:即WebAppListener中的WebListener注解
第二种:通过SpringBean注入
SpringBean注入监听器
七、测试监听器启动程序,查看监听器是否执行
感谢各位的关注。如有问题,欢迎指正;如有建议,请多指教。
最后附上源代码:https://github.com/zhangyd-c/springboot/tree/master/springboot-servlet
我就是我,不一样的烟火。