多个OncePerRequestFilter过滤器实现的使用及顺序
作用
- 在一次外部请求中只过滤一次, 对于服务器内部之间的forward等请求,不会再次执行过滤方法
- 可以定义多个实现类, 各自处理各自的过滤工作, 并指定过滤顺序
使用场景
- token校验有效性
- Xss处理
- 敏感词汇过滤 …
场景案例
芋道中的过滤器顺序定义
public interface WebFilterOrderEnum {int CORS_FILTER = Integer.MIN_VALUE;int TRACE_FILTER = CORS_FILTER + 1;int ENV_TAG_FILTER = TRACE_FILTER + 1;int REQUEST_BODY_CACHE_FILTER = Integer.MIN_VALUE + 500;// OrderedRequestContextFilter 默认为 -105,用于国际化上下文等等int TENANT_CONTEXT_FILTER = - 104; // 需要保证在 ApiAccessLogFilter 前面int API_ACCESS_LOG_FILTER = -103; // 需要保证在 RequestBodyCacheFilter 后面int XSS_FILTER = -102; // 需要保证在 RequestBodyCacheFilter 后面// Spring Security Filter 默认为 -100,可见 org.springframework.boot.autoconfigure.security.SecurityProperties 配置属性类int TENANT_SECURITY_FILTER = -99; // 需要保证在 Spring Security 过滤器后面int FLOWABLE_FILTER = -98; // 需要保证在 Spring Security 过滤后面int DEMO_FILTER = Integer.MAX_VALUE;}
使用
当前过滤器为定义在springboot组件中, 使用springboot的自动装配进行引入的
故使用的 方法1
- 方法1. 创建FilterRegistrationBean< T extends Filter>对象,指定过滤器,并指定顺序 + @Bean + @AutoConfiguration 方式
- 方法2. 单体架构为了方便 可以在@Component+@Order() 放在过滤器类上
1.定义过滤器
import cn.hutool.core.util.StrUtil;
import com.caeri.framework.common.pojo.CommonResult;
import com.caeri.framework.common.util.servlet.ServletUtils;
import com.caeri.framework.web.core.util.WebFrameworkUtils;
import org.springframework.web.filter.OncePerRequestFilter;import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import static com.caeri.framework.common.exception.enums.GlobalErrorCodeConstants.DEMO_DENY;/*** 演示 Filter,禁止用户发起写操作,避免影响测试数据** @author 芋道源码*/
public class DemoFilter extends OncePerRequestFilter {// 定义哪些请求进入过滤器 (不定义则全部都进入)// 可以将需要过滤的情况定义出来,加上 !@Overrideprotected boolean shouldNotFilter(HttpServletRequest request) {String method = request.getMethod();return !StrUtil.equalsAnyIgnoreCase(method, "POST", "PUT", "DELETE") // 写操作时,不进行过滤率|| WebFrameworkUtils.getLoginUserId(request) == null; // 非登录用户时,不进行过滤}// 过滤器需要执行的逻辑@Overrideprotected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) {// todo 执行逻辑// 继续过滤chain.doFilter(request,response);}}
2.自动配置类中定义Bean
@AutoConfiguration
public class WebAutoConfiguration {@Bean@ConditionalOnProperty(value = "yudao.demo", havingValue = "true")public FilterRegistrationBean<DemoFilter> demoFilter() {// 过滤器注册BeanFilterRegistrationBean<DemoFilter> bean = new FilterRegistrationBean<>(new DemoFilter());// 设置顺序, 通过上面定义枚举来统一管理bean.setOrder(WebFilterOrderEnum.DEMO_FILTER);return bean;}
}