Springboot整合Filter

1,方式一

  【1】通过注解扫描完成Filter组件注册

 

/*@WebFilter(filterName = "FirstFilter",urlPatterns = {"*.do","*.jsp"})*/
@WebFilter(filterName = "FirstFilter",urlPatterns = "/first")
public class FirstFilter implements Filter {


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("进入FirstFilter...");
     filterChain.doFilter(servletRequest,servletResponse); System.out.println(
"退出FirstFilter..."); } @Override public void destroy() { } }

 

 

 

  【2】修改启动类

 

@SpringBootApplication
@ServletComponentScan//在Spring Boot启动时会扫描@WebFiter注解,并将该类实例
public class SpringbootwebApplication {

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

}

 

2,方式二

  【1】通过方法完成Filter组件注册

 

public class SecondFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("进入SecondFilter...");
        filterChain.doFilter(servletRequest,servletResponse);
        System.out.println("退出SecondFilter...");
    }

    @Override
    public void destroy() {

    }
}

 

 

 

  【2】创建Filter配置类

 

@Configuration
public class FilterConfig {
    @Bean
    public FilterRegistrationBean getFilterRegistrationBean()
    {
        FilterRegistrationBean bean = new FilterRegistrationBean(new SecondFilter());
        /*bean.addUrlPatterns(new String[]{"*.do","*.jsp"});*/
        bean.addUrlPatterns("/second");
        return bean;
    };
}

 

posted @ 2020-04-13 13:27  拯代码  阅读(475)  评论(0编辑  收藏  举报