SpringBoot2整合Filter

1.方法一:注解方式,这种方式可以注入容器里的bean

@Component
@WebFilter(filterName = "test1" ,urlPatterns = "/*")
public class TestFilterOrder implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.info("filter start");
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }
}

 

方法二:注解方式


@WebFilter(filterName = "test1" ,urlPatterns = "/*")
public class TestFilterOrder implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.info("filter start");
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }
}
@ServletComponentScan(basePackages = "com.mmall.controller.common.filters")
public class MyMmallApplication {

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

}

方法一和方法二可以在Filter里@autowire其他的Bean,方法三不能自动装配

方法三:配置类,可以设置Filter顺序,Order越小越先执行

@Configuration
public class FilterConfig {

    @Bean
    public FilterRegistrationBean testFilterOrder(){
        FilterRegistrationBean sessionExpireFilterFilterRegistrationBean = new FilterRegistrationBean<>(new TestFilterOrder());
        sessionExpireFilterFilterRegistrationBean.setName("testFilterOrder");
        ArrayList urls = new ArrayList<>();
        urls.add("*.do");
        sessionExpireFilterFilterRegistrationBean.setUrlPatterns(urls);
        sessionExpireFilterFilterRegistrationBean.setOrder(3);
        return sessionExpireFilterFilterRegistrationBean;
    }

    @Bean
    public FilterRegistrationBean testFilterOrder2(){
        FilterRegistrationBean sessionExpireFilterFilterRegistrationBean = new FilterRegistrationBean<>(new TestFilterOrder2());
        sessionExpireFilterFilterRegistrationBean.setName("testFilterOrder2");
        ArrayList urls = new ArrayList<>();
        urls.add("*.do");
        sessionExpireFilterFilterRegistrationBean.setUrlPatterns(urls);
        sessionExpireFilterFilterRegistrationBean.setOrder(2);
        return sessionExpireFilterFilterRegistrationBean;
    }
}

SpringBoot2整合Filter_第1张图片 

同时有配置的类和注解方式的话,filter顺序:首先是用配置文件配置的Filter(按照Order顺序),然后是WebFilter注解配置的。

你可能感兴趣的:(Spring)