美文网首页
Springboot 自定义过滤器

Springboot 自定义过滤器

作者: 白驹过隙_忽然而已 | 来源:发表于2019-01-07 17:49 被阅读0次
    //@WebFilter(filterName="MyFilter",urlPatterns="/*")
    //@Order(2) //设置spring  bean 的加载顺序(未实验),不代表Filter的优先级
    public class Myfilter implements Filter{
      @Override
      public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("Filter1 Init-------------->");
      }
      @Override
      public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 
                                                                  throws IOException, ServletException {
      log.info("Filter1 processing----------->");
      chain.doFilter(request, response);
      /*log.info("URL---->"+request.getProtocol());
      log.info("SERVERPort--->"+request.getServerPort());
      log.info("ContentType---->"+request.getContentType());
      log.info("ENCODING---->"+request.getCharacterEncoding());
      log.info("IP---->"+request.getRemoteAddr());
      log.info("HOST---->"+request.getRemoteHost());
      log.info("REMO PORT---->"+request.getRemotePort());*/
    }
    /**
    * 停止项目时过滤器销毁
    */
      @Override
      public void destroy() {
        log.info("Filter1 destory----------------->");
      }
    
    }
    
    public class Myfilter2 implements Filter{
            //内容略。。。。。
    }
    
    /**
    *配置类,配置过滤器以及优先级(bean.setOrder())
    */
    @Configuration
    public class WebMVCConfig {
      @Bean
      public FilterRegistrationBean configureFilter1(){
        FilterRegistrationBean bean = new FilterRegistrationBean<>();
        bean.setName("filter1");
        Myfilter myfilter = new Myfilter();
        bean.setFilter(myfilter);
        bean.setOrder(2);
        List<String> urlList = new ArrayList<String>();
        urlList.add("/*");
        bean.setUrlPatterns(urlList);
        return bean;
    }
    
      @Bean
      public FilterRegistrationBean configureFilter2(){
        FilterRegistrationBean bean = new FilterRegistrationBean<>();
        bean.setName("filter2");
        MyFilter2 myfilter2 = new MyFilter2();
        bean.setFilter(myfilter2);
        bean.setOrder(1);
        List<String> urlList = new ArrayList<String>();
        urlList.add("/*");
        bean.setUrlPatterns(urlList);
        return bean;
      }
    }
    

    以上是一种方式,还有一种基于注解的方式,@WebFilter(filterName="过滤器名称",urlPatterns="过滤器监控的路径") ,需要在启动类加上@ServletComponentScan注解,但是此方法不清楚如何配置过滤器的优先级

    相关文章

      网友评论

          本文标题:Springboot 自定义过滤器

          本文链接:https://www.haomeiwen.com/subject/mwqprqtx.html