方式1:
①实现接口javax.servlet.Filter,重写Filter的doFilter等方法,并用javax.servlet.annotation.WebFilter注解指定过滤路径
package com.example.demo.filter;
...
@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("自定义MyFilter");
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
}
}
②启动类添加Filter扫描注解 org.springframework.boot.web.servlet.ServletComponentScan,扫描指定包
@SpringBootApplication
@ServletComponentScan(basePackages = {"com.example.demo.servlet", "com.example.demo.filter"})
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
方式2:
①实现接口javax.servlet.Filter,重写Filter的doFilter等方法
package com.example.demo.filter;
...
public class MyConfFilter 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("自定义MyConfFilter");
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
}
}
②编写Filter配置类,配置自定义的Filter
package com.example.demo.config;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
...
@Configuration //配置类
public class FilterConfig {
@Bean //注册为FilterRegistrationBean
public FilterRegistrationBean myConfFilterRegistrationBean() {
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new MyConfFilter());
filterRegistrationBean.addUrlPatterns("/*");
return filterRegistrationBean;
}
}