springboot中Filter的使用相关

springboot集成Filter有2种方式


1、
@Bean
public FilterRegistrationBean<Filter> filterRegistrationBean(WebEndpointProperties webEndpointProperties, CustomizeFilter filter) {
FilterRegistrationBean<Filter> bean = new FilterRegistrationBean();
bean.setFilter(filter);
List<String> pathList = new ArrayList();
pathList.add(webEndpointProperties.getBasePath() + "/*");
bean.setUrlPatterns(pathList);
   bean.setOrder(0);
return bean;
}
FilterRegistrationBean:设置过滤器的一些属性
以上代码的作用:只有/actuator开头的请求地址才会走过滤器,即走到//TODO  过滤逻辑
@Bean
public CustomizeFilter customizeFilter() {
return new CustomizeFilter();
}
public class CustomizeFilter implements Filter{
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
      //TODO 过滤逻辑
      request.getHeader("token")//前端传入,后端可以在此处做拦截校验,后端同样配置一个token,不满足则这个接口就不能用
  }    

}


2、这种方式无法指定Filter链的执行顺序,只能按照类名来顺序执行

  @WebFilter(urlPatterns = "/*", filterName = "myFilter")
  public class MyFilter implements Filter {

  //TODO

 

 




posted @ 2021-06-01 10:01  龙之谷2019  阅读(102)  评论(0编辑  收藏  举报