Springboot整合Filter

Posted 拯代码

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
    };
}

 

以上是关于Springboot整合Filter的主要内容,如果未能解决你的问题,请参考以下文章

SpringBoot: 3.SpringBoot整合filter(转)

SpringBoot整合Filter

全栈编程系列SpringBoot整合Shiro(含KickoutSessionControlFilter并发在线人数控制以及不生效问题配置启动异常No SecurityManager...)(代码片段

Springboot整合Filter

SpringBoot-- 整合ServletFilterListener

springboot Thymeleaf 整合