一、使用注解方式实现
1、使用Servlet3注解过滤器
@WebFilter(urlPatterns = "/*")
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("进入Filter过滤器。。");
filterChain.doFilter(servletRequest,servletResponse);
}
@Override
public void destroy() {
}
}
2、在main方法添加注解
@ServletComponentScan(basePackages = {"com.example.springboot.servlet","com.example.springboot.filter"})
二、通过SpringBoot配置类实现
1、编写一个普通servlet类
public class HeFilter 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("he filter 进入Filter过滤器。。");
filterChain.doFilter(servletRequest,servletResponse);
}
@Override
public void destroy() {
}
}
2、编写一个springboot配置类
@Bean
public FilterRegistrationBean heFilterRegistrationBean() {
FilterRegistrationBean registration = new FilterRegistrationBean(new HeFilter());
registration.addUrlPatterns("/*");
return registration;
}