方式一
自定义Filter类实现Filter接口,添加@WebFilter注解
@WebFilter(urlPatterns = "/*", filterName = "helloFilter")
public class HelloFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("================init filter===================");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("=================this is filer method====================");
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
System.out.println("==========================destroy method===================");
}
}
在SpringBoot项目启动类上加@ServletComponentScan注解
@SpringBootApplication
// SpringBoot启动时自动扫描@WebServlet和@WebFilter
@ServletComponentScan
public class SpringbootDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootDemoApplication.class, args);
}
}
访问测试
http://localhost:8081/hello?name=SpringBoot
方式二
自定义Filter类实现Filter接口,但是不需要添加@WebFilter注解
public class TestFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("================init filter===================");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("=================this is filer method====================");
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
System.out.println("==========================destroy method===================");
}
}
启动类中注册filter为一个bean
注意:在SpringBoot项目启动类上不需要加@ServletComponentScan注解
@SpringBootApplication
public class SpringbootDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootDemoApplication.class, args);
}
@Bean
public FilterRegistrationBean getFilterRegistrationBean() {
FilterRegistrationBean registrationBean = new FilterRegistrationBean(new TestFilter());
registrationBean.addUrlPatterns("/test");
return registrationBean;
}
}
测试
版权声明:本文为luciferlongxu原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。