说在前面
Filter简介:https://blog.csdn.net/Soinice/article/details/82787964
上一篇文章已经对定义Servlet 的方法进行了说明,过滤器(Filter)的注册方法和 Servlet 一样,不清楚的可以查看下上一篇文章:https://blog.csdn.net/Soinice/article/details/82757376
在spring boot中添加自己的Filter有两种方法,代码注册Filter和注解自动注册(Servlet和Listener也是如此)。
一、代码注册通过FilterRegistrationBean 获得控制。 也可以通过实现 ServletContextInitializer 接口直接注册。
二、在 SpringBootApplication 上使用@ServletComponentScan注解后,Filter可以直接通过 @WebFilter注解自动注册,无需其他代码。
在pom.xml加入相关依赖
当然,通过idea 创建默认spring boot web 项目,会默认含有这个属性
1)通过FilterRegistrationBean进行代码注册
编写过滤器 Filter
注册过滤器 Filter
将 Filter 注册成 Bean。添加到过滤器链中,此方式适用于使用第三方的过滤器。在上文创建的 WebMvcConfig类中添加如下代码:
页面访问
2)通过注解@ServletComponentScan进行代码注册
编写过滤器 Filter
在Filter 类添加注解@WebFilter:
注册过滤器 Filter
将 Servelt 进行组件扫描。在应用启动SpringBootDemoApplication类中添加注解@ServletComponentScan:
页面访问
总结
当有多个过滤器需要按顺序执行时怎么办?
使用注解的配置方法不能配置顺序,但是可以通过过滤器名字的字典顺序实现顺序过滤(比如AFilter就会在BFilter前执行),显然这种方法看起来不怎么正经。
但是我们可以使用第二种配置方法.
通过给注册类设置order,order越小,执行优先级越高
源码下载
[相关示例完整代码]请获取 相关分支哦:feature-20180910-web