FilterChain:在处理某些复杂的业务时,一个过滤器不够,可以设计多个过滤器共同完成过滤任务,形成过滤器链
1.多个filter和目标资源在一次http请求,在同一个线程中
2.当一个请求url和filter的url-pattern匹配时,才会被执行,如果有多个匹配上,就会顺序执行,形成一个filter调用链
3.多个filter共同执行时,因为是一次http请求,使用同一个request对象
4.多个filter执行顺序,和web.xml配置顺序是一致的
5.chain.doFilter(req,resp)方法将执行下一个(匹配上的)过滤器的doFilter方法,如果后面没有过滤器,则执行目标资源
6.注意执行过滤器链时,顺序是(用上面的案例分析)Http请求->A过滤器doFilter->A过滤器前置代码->A过滤器chain.doFilter()
->B过滤器doFilter->B过滤器前置代码->B过滤器chain.doFilter()->目标文件->B过滤器后置代码->A过滤器后置代码
<filter>
<filter-name>AFilter</filter-name>
<filter-class>com.filter.AFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>AFilter</filter-name>
<url-pattern>/admin/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>BFilter</filter-name>
<filter-class>com.filter.BFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>BFilter</filter-name>
<url-pattern>/admin/*</url-pattern>
</filter-mapping>
package com.filter;
import javax.servlet.*;
import java.io.IOException;
public class AFilter 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("AFilter doFilter的前置代码...");
System.out.println("执行AFilter doFilter()");
filterChain.doFilter(servletRequest,servletResponse);
System.out.println("AFilter doFilter的后置代码...");
}
@Override
public void destroy() {
}
}
package com.filter;
import javax.servlet.*;
import java.io.IOException;
public class BFilter 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("BFilter doFilter的前置代码...");
System.out.println("执行BFilter doFilter()");
filterChain.doFilter(servletRequest,servletResponse);
System.out.println("BFilter doFilter的后置代码...");
}
@Override
public void destroy() {
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>hi</title>
</head>
<body>
<h1>admin目录下的 hi.jsp</h1>
<h1>后台管理</h1>
<a href="#">用户列表</a>||<a href="#">添加用户</a>||<a href="#">删除用户</a>
<hr/>
</body>
</html>