SpringBoot - 使用Filter
Posted Simple°
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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
打印:
以上是关于SpringBoot - 使用Filter的主要内容,如果未能解决你的问题,请参考以下文章