关于过滤器和拦截器,一直容易混乱,小记一下。
对比
- Filter是servlet的规范,是web三大组件之一(Servlet,Filter,Listener),不依赖于spring;
- 拦截器是一些框架中的概念,比如:Spring,用于拦截请求和响应的处理过程。拦截器通常是在Spring MVC的上下文中使用的,提供了对控制器(Controller)方法的拦截能力
- 过滤器和拦截器功能类似,都是对请求预处理和拦截,
- 都是链式的,Filter没有执行chain.doFilter或者拦截器的prehandler没有返回true,请求不再继续传递。
过滤器
在spring中,过滤器可以通过继承OncePerRequestFilter
java
@Order(998)
@Component
public class MyFilter01 extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
System.out.println("自定义Filter01");
filterChain.doFilter(request,response);
}
}
实现源生Filter
java
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 javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;
public class TraceIdFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// 初始化代码(如果需要)
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
String traceId = httpRequest.getHeader("Trace-ID");
if (traceId == null || traceId.isEmpty()) {
traceId = UUID.randomUUID().toString();
}
TraceIdHolder.setTraceId(traceId);
httpResponse.setHeader("Trace-ID", traceId);
try {
chain.doFilter(request, response);
} finally {
TraceIdHolder.clear();
}
}
@Override
public void destroy() {
// 销毁代码(如果需要)
}
}
// 注册
@Configuration
public class FilterConfig {
@Bean
public FilterRegistrationBean<TraceIdFilter> traceIdFilter() {
FilterRegistrationBean<TraceIdFilter> registrationBean = new FilterRegistrationBean<>();
registrationBean.setFilter(new TraceIdFilter());
registrationBean.addUrlPatterns("/*"); // 过滤所有路径
return registrationBean;
}
}
拦截器
拦截器可以实现HandlerInterceptor
接口(需要注册)
java
//定义
public class MyInterceptor01 implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("自定义拦截器01");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
// 注册
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MyInterceptor02()).order(667);
registry.addInterceptor(new MyInterceptor01()).order(666);
}
}