1、自定义过滤器
public class MyFilter 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("进入过滤器"); filterChain.doFilter(servletRequest,servletResponse); } @Override public void destroy() { } }
2、注册过滤器
@Configuration public class MyFilterConfig { @Bean public FilterRegistrationBean myFiletr(){ FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new MyFilter()); filterRegistrationBean.addUrlPatterns("/*"); return filterRegistrationBean; } }
3、测试
运行,我们的过滤路径是/*,所以我们通过调用任何接口都可以在控制台出现我们要过滤的规则
开发过程中,根据需求定义过滤器或者拦截器