码迷,mamicode.com
首页 > 编程语言 > 详细

SpringBoot - 使用Filter

时间:2018-10-06 20:35:58      阅读:298      评论:0      收藏:0      [点我收藏+]

标签: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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!