一、通过注解方式实现
1. 通过注解方式创建一个Filer
@WebFilter(filterName = "MyFilter", urlPatterns = "/*")
public class MyFilter implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
System.out.println("-----doFilter-----");
chain.doFilter(req, resp);
}
public void init(FilterConfig config) throws ServletException {
}
}
2. 在主应用程序Application类上添加注解
注解:@ServletComponentScan("com.suke.springboot.web")
@SpringBootApplication
@ServletComponentScan("com.suke.springboot.web")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
3. 启动应用SpringBoot,浏览器访问测试
二、通过Spring Boot的配置类实现
1. 创建一个普通的Filter
@WebFilter(urlPatterns = "/*")
public class HeFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("He已进入Filter过滤器,您的请求正常,请继续遵循规则...");
filterChain.doFilter(servletRequest,servletResponse);
}
}
2. 编写一个Spring Boot的配置类,在该类中注册Filter
@Configuration //该注解将此类标记为配置类
public class FilterConfig {
@Bean
public FilterRegistrationBean heFilterRegistration() {
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new HeFilter());
filterRegistrationBean.addUrlPatterns("/*");
return filterRegistrationBean;
}
}