SpringBoot整合Filter过滤器的两种方式:
1.通过扫描注解完成Filter组件注册
创建一个类,实现Filter接口,实现doFilter()方法
在该类使用注解@WebFilter,设置filterName与urlPatterns
在doFilter中编写代码
编写启动类:增加注解@ServletComponentScan
/**
* SpringBoot整合Filter 方式一
*/
//@WebFilter(filterName="FirstFilter" , urlPatterns= {"*.do","*.jsp"})
@WebFilter(filterName="FirstFilter" , urlPatterns= "/first")
public class FirstFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
System.out.println("进入Filter");
chain.doFilter(request, response);
System.out.println("离开Filter");
}
}
@SpringBootApplication
@ServletComponentScan
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
urlPatterns 是数组类型的,可以拦截多个 例如:urlPatterns= {".do",".jsp"}
2.通过方法完成Filter组件注册
- 创建一个类,实现Filter接口,实现doFilter()方法
- 编写启动类
- 添加一个方法,返回值必须是FilterRegistrationBean的对象,他能够创建Filter对象的实例对象
- 创建FilterRegistrationBean对象,传入实例化的Filter对象
- 添加Url,bean.addUrlPatterns();
- 返回FilterRegistrationBean对象
- 在此方法上增加@Bean的注解
/**
* 注册Filter
*/
@Bean
public FilterRegistrationBean getFilterRegistrationBean() {
FilterRegistrationBean bean = new FilterRegistrationBean(new SecondFilter());
//bean.addUrlPatterns(new String[] {"*.do","*.jsp"});
bean.addUrlPatterns("/second");
return bean;
}