public final class ApplicationFilterChain implements FilterChain {
/**
* Filters. ApplicationFilterConfig封装了匹配当前请求的所有filter
* (注意这里并不是所有的filter,匹配的过程是tomcat自己做的)
* (并且执行完请求后,这个数据的每个元素都会release掉,即置为null)
*/
private ApplicationFilterConfig[] filters = new ApplicationFilterConfig[0];
/**
* The int which is used to maintain the current position
* in the filter chain.
*/
private int pos = 0; // 索引, 当前执行的filter在上面这个数组中的位置
/**
* The int which gives the current number of filters in the chain.
*/
private int n = 0; // 一共配置的filter的数量
/**
* The servlet instance to be executed by this chain.
*/
private Servlet servlet = null;
@Override
public void doFilter(ServletRequest request, ServletResponse response)
throws IOException, ServletException {
if( Globals.IS_SECURITY_ENABLED ) {
final ServletRequest req = request;
final ServletResponse res = response;
try {
java.security.AccessController.doPrivileged(
new java.security.PrivilegedExceptionAction<Void>() {
@Override
public Void run()
throws ServletException, IOException {
internalDoFilter(req,res);
return null;
}
}
);
} catch( PrivilegedActionException pe) {
Exception e = pe.getException();
if (e instanceof ServletException)
throw (ServletException) e;
else if (e instanceof IOException)
throw (IOException) e;
else if (e instanceof RuntimeException)
throw (RuntimeException) e;
else
throw new ServletException(e.getMessage(), e);
}
} else {
internalDoFilter(request,response); // 调用下面这个方法
}
}
private void internalDoFilter(ServletRequest request,
ServletResponse response)
throws IOException, ServletException {
// Call the next filter if there is one
// 0 -> 2 ,假设一共有两个Filter
// 第一轮: pos = 0, n = 2, 做判断 0 < 2, 好,这个时候pos + 1 所以此时pos = 1
// 假设此时的第一个Filter没有调用chain.doFilter(req,resp)方法,那么会执行下面的return;
// 就不会执行下面的servlet调用service方法了
// 假设第一轮中,调用了chain.doFilter,这个,又回到上面这个方法,接着又调用本方法, 注意此时是同一个FilterChain
// 此时 pos = 1, 所以 1 < 2, 依旧成立, 好,这个时候pos + 1 所以此时pos = 2
// 假设第二个过滤器如果又没调用chain.doFilter那么filter.doFilter(request, response, this);
// 这一句又断了,就直接执行return;
// 就不会执行下面的servlet调用service方法了
// 第二轮: 假设第二轮调用了,那么又会回到当前的方法2<2不成立, 那么就会执行下面的servlet调用service方法了
// 其实chain.doFilter可以这样理解,chain把过滤的具体功能交给filter来实现, 而filter做完自己的过滤功能后,
// 因为已经拿到了chain, 那么就有权决定,是否要把执行权交回给chain, 如果不交回, 那么chain就断了。
// =========这是责任链模式的另外一种用法========
// 思考: 假设其中某一个Filter, 它不是在最后一句调用的filterChain.doFilter
// 那么其实也实现了spring mvc的拦截器一样的功能,等servlet处理完了之后,
// 然后逆序调用filter的那句话后面的代码,
// 特别注意: 这个时候处理完的request和response已经让servlet处理过了,
// 所以filter可以继续接着对这个处理完成了的请求中的request和response对象处理
// 然后再返回给客户端。
// 假设很多个过滤器, 前面几个都通过了,但是被一个给拦住了,那么也会逆序回调过滤器dofilter代码之后面的代码
if (pos < n) { //
ApplicationFilterConfig filterConfig = filters[pos++]; // 根据索引找filter
try {
Filter filter = filterConfig.getFilter(); // 先获取到filter,如果之前创建过,直接返回,如果没有,
// 那么通过反射创建,并回调初始化方法,然后传个东西给
// 它。注意这里的filterConfig是
// ApplicationFilterConfig。
// 下面分析以下ApplicationFilterConfig
// ApplicationFilterChain中组合了配置的Filter,并都封装成了ApplicationFilterConfig数组,
// 并且ApplicationFilterConfig中封装了我们配置的filter的所有相关信息,创建filter也是由
// ApplicationFilterConfig这个对象创建的。所以tomcat读取web.xml中的filter时,创建的并不是
// Filter,而是ApplicationFilterConfig,由这个类来对filter的配置信息做一个封装。真正执行的时候
// 从ApplicationFilterConfig类中获取filter,如果之前创建过,那么直接返回,如果之前没有创建过,
// 那么通过反射创建Filter,创建好后。
// 调用Filter的init方法,并且把当前对象this,也就是ApplicationFilterConfig,传进去。因为
// ApplicationFilterConfig还实现了FilterCOnfig接口,它里面还封装了Context,而从Context里面
// 由能拿到ServletContext。
// 所以filter重写的init方法中的filterConfig实际上就是ApplicationFilterconfig
if (request.isAsyncSupported() && "false".equalsIgnoreCase(
filterConfig.getFilterDef().getAsyncSupported())) {
request.setAttribute(Globals.ASYNC_SUPPORTED_ATTR, Boolean.FALSE);
}
if( Globals.IS_SECURITY_ENABLED ) {
final ServletRequest req = request;
final ServletResponse res = response;
Principal principal =
((HttpServletRequest) req).getUserPrincipal();
Object[] args = new Object[]{req, res, this};
SecurityUtil.doAsPrivilege ("doFilter", filter, classType, args, principal);
} else {
filter.doFilter(request, response, this);
}
} catch (IOException | ServletException | RuntimeException e) {
throw e;
} catch (Throwable e) {
e = ExceptionUtils.unwrapInvocationTargetException(e);
ExceptionUtils.handleThrowable(e);
throw new ServletException(sm.getString("filterChain.filter"), e);
}
return; // 这个return;语句是关键,如果中间的FilterChain断了的话,
// 那么会直接到这里来,下面调用servlet的方法也不会执行了
}
// We fell off the end of the chain -- call the servlet instance
try {
if (ApplicationDispatcher.WRAP_SAME_OBJECT) {
lastServicedRequest.set(request);
lastServicedResponse.set(response);
}
if (request.isAsyncSupported() && !servletSupportsAsync) {
request.setAttribute(Globals.ASYNC_SUPPORTED_ATTR,
Boolean.FALSE);
}
// Use potentially wrapped request from this point
if ((request instanceof HttpServletRequest) &&
(response instanceof HttpServletResponse) &&
Globals.IS_SECURITY_ENABLED ) {
final ServletRequest req = request;
final ServletResponse res = response;
Principal principal =
((HttpServletRequest) req).getUserPrincipal();
Object[] args = new Object[]{req, res};
SecurityUtil.doAsPrivilege("service",
servlet,
classTypeUsedInService,
args,
principal);
} else {
// 上面的过滤器执行完了,才轮到servlet去处理这个请求
// 注意:这里不一定执行完了, 可以看下上面的思考
servlet.service(request, response);
}
} catch (IOException | ServletException | RuntimeException e) {
throw e;
} catch (Throwable e) {
e = ExceptionUtils.unwrapInvocationTargetException(e);
ExceptionUtils.handleThrowable(e);
throw new ServletException(sm.getString("filterChain.servlet"), e);
} finally {
if (ApplicationDispatcher.WRAP_SAME_OBJECT) {
lastServicedRequest.set(null);
lastServicedResponse.set(null);
}
}
}
}
Tomcat中的filter调用doFilter的问题
于 2020-11-08 15:32:21 首次发布