SpringBoot - 使用Filter

2021-05-16 21:29

阅读:670

标签:int   pre   run   sys   etc   扫描   注册   servlet   spring   

1、在SpringBoot中使用Filter

1.1、使用注解注册Filter:

/**
 * SpringBoot使用Filter
 */
@WebFilter(filterName="OneFilter",urlPatterns="/one")
public class OneFIlter 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("start OneFilter ...");
        filterChain.doFilter(servletRequest, servletResponse);
        System.out.println("end OneFilter ...");
    }

    @Override
    public void destroy() {
    }
}

 

@SpringBootApplication
//在 springBoot 启动时会扫描@WebFilter并实例化
@ServletComponentScan
public class AppOne {
    public static void main(String[] args) {
        SpringApplication.run(AppOne.class, args);
    }
}

 

访问:http://localhost:8080/one

技术分享图片

  

后台打印:

 技术分享图片

 

 

1.2、另一种初始化Filter的方法:方法注册

/**
 * SpringBoot使用Filter
 */
public class TwoFilter 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("start TwoFilter ...");
        filterChain.doFilter(servletRequest, servletResponse);
        System.out.println("end TwoFilter ...");
    }

    @Override
    public void destroy() {
    }
}

 

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

    @Bean
    public FilterRegistrationBean registrationFilterBean(){
        FilterRegistrationBean bean = new FilterRegistrationBean(new  TwoFilter());
//        过滤多个url,可以使用字符串数组
//        bean.addUrlPatterns(new String[]{"*.do","*.jsp"});
        bean.addUrlPatterns("/two");
        return bean;
    }
}

 

访问:http://localhost:8080/two

 技术分享图片

 

打印:

 技术分享图片

 

SpringBoot - 使用Filter

标签:int   pre   run   sys   etc   扫描   注册   servlet   spring   

原文地址:https://www.cnblogs.com/simple-ly/p/9748197.html


评论


亲,登录后才可以留言!