定义过滤器的执行顺序
1、第一个过滤器
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;public class MyFirstFilter implements Filter {@Overridepublic void init(FilterConfig filterConfig) throws ServletException {// 初始化逻辑}@Overridepublic void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)throws IOException, ServletException {System.out.println("执行 MyFirstFilter...");// 继续执行过滤器链chain.doFilter(request, response);}@Overridepublic void destroy() {// 清理逻辑}
}
第二个过滤器
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;public class MySecondFilter implements Filter {@Overridepublic void init(FilterConfig filterConfig) throws ServletException {// 初始化逻辑,如果需要的话}@Overridepublic void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)throws IOException, ServletException {// 你的自定义过滤器逻辑在这里System.out.println("执行 MySecondFilter...");// 继续执行过滤器链chain.doFilter(request, response);}@Overridepublic void destroy() {// 清理逻辑,如果需要的话}
}
定义过滤器的执行顺序的配置
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;@Configuration
public class FilterConfig {@Beanpublic FilterRegistrationBean<MyFirstFilter> myFirstFilter() {FilterRegistrationBean<MyFirstFilter> registrationBean = new FilterRegistrationBean<>();registrationBean.setFilter(new MyFirstFilter());registrationBean.addUrlPatterns("/*");registrationBean.setOrder(1);return registrationBean;}@Beanpublic FilterRegistrationBean<MySecondFilter> mySecondFilter() {FilterRegistrationBean<MySecondFilter> registrationBean = new FilterRegistrationBean<>();registrationBean.setFilter(new MySecondFilter());registrationBean.addUrlPatterns("/*");registrationBean.setOrder(2);return registrationBean;}
}
定义controller
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
public class HelloController {@RequestMapping("/hello")public String hello() {return "hello filter!";}
}
正常访问:http://localhost:8080/hello
不正常访问:http://localhost:8080/HELLO
可看到路径mapping是区分大小写的,如果路径不正确,虽然404,但过滤器链依然会执行(/*全局情况下)。