Filter 是 JavaEE 中 Servlet 规范的一个组件,位于包javax.servlet 中,它可以在 HTTP 请求到达 Servlet 之前,被一个或多个Filter处理。
1.案例结构
1.1first拦截器
@WebFilter(filterName = "first" , urlPatterns = "/*")
@Order(1)
public class FirstFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
Filter.super.init(filterConfig);
System.out.println("first拦截器初始化");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) servletRequest;
System.out.println("first拦截器获取Attribute"+req.getAttribute("name"));//无
req.setAttribute("name","第一次设置的name");//作用范围为:一次请求域,即下次Filter也能取的到
HttpServletResponse res = (HttpServletResponse) servletResponse;
res.setHeader("firstHeader","firstHeader");//设置请求头,会一直层层传递到控制层的响应头
filterChain.doFilter(req,res);//按Order优先顺序调用下一个Filter,直到Controller层
System.out.println("firstFilterEnd");//doFilter内部执行完毕之后,才回来执行这个,类似二叉树的前序遍历
}
@Override
public void destroy() {
Filter.super.destroy();
System.out.println("first拦截器销毁");
}
}
1.2second拦截器
@WebFilter(urlPatterns = "/*")
@Order(2)
public class SecondFilte