SpringBoot - 使用Filter
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); } }
后台打印:
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
打印: