Spring Boot配置Filter

此博客是学习Spring Boot过程中记录的,一来为了加深自己的理解,二来也希望这篇博客能帮到有需要的朋友.同时如果有错误,希望各位不吝指教

一.通过注入Bean的方式配置Filter:

注意:此方法所在的类一定要添加了@Configuration注解,或者是直接放在主类

@Bean
public FilterRegistrationBean<Filter> myFilter(){
   //用于注册Filter
    FilterRegistrationBean<Filter> filter = new FilterRegistrationBean<>();
    //new的是自己自定义的Filter
    filter.setFilter(new MyFilter());
  
//设置此过滤器的执行顺序的优先级,越小优先级越高 filter.serOrder(1); return filter; }

  

自定义Filter类,实现javax.servlet.Filter

public class MyFilter implements Filter {
    public static final List<String> EXCLUSIONS_PATH = Arrays.asList("*.js","*.css","/druid/*");
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String uri = request.getRequestURI();
        if (EXCLUSIONS_PATH.contains(uri)){
            filterChain.doFilter(servletRequest,servletResponse);
        } else{
            System.err.println(uri + "被拦截");
        }
    }
}

 

二:通过注解配置Filter

自定义的Filter类:

//声明这是一个Filter类
@WebFilter(filterName = "myFilter",urlPatterns = "/*")
//配置过滤器的优先级 @Order(
1) public class MyFilter implements Filter { public static final List<String> EXCLUSIONS_PATH = Arrays.asList("*.js","*.css","/druid/*"); @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; String uri = request.getRequestURI(); if (EXCLUSIONS_PATH.contains(uri)){ filterChain.doFilter(servletRequest,servletResponse); } else{ System.err.println(uri + "被拦截"); } } }

  

主类添加注解:@ServletCompontScan

@SpringBootApplication
//可以不指定包,会扫描全部的包会扫描添加了@WebServlet、@WebFilter、@WebListener注解的类,并注册的Spring容器
@ServletComponentScan(basePackages = {"com.cjx.filter"})
public class SpringbootApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootApplication.class, args);
    }

}

 

posted @ 2020-07-09 12:47  Java挖坑工程师  阅读(433)  评论(0编辑  收藏  举报