HandlerExecutionChain类比较简单,好理解。
/*
* 处理器执行链由处理器对象和拦截器组成。
*/
public class HandlerExecutionChain {
下面是类的部分属性。
private final Object handler; //处理器对象。
private HandlerInterceptor[] interceptors; //拦截器数组
private List<HandlerInterceptor> interceptorList; //拦截器列表
/**
* Apply preHandle methods of registered interceptors.
* @return {@code true} if the execution chain should proceed with the
* next interceptor or the handler itself. Else, DispatcherServlet assumes
* that this interceptor has already dealt with the response itself.
* 执行已经注册的拦截的 preHandle()方法。如果返回true,则执行链可以执行下一个拦截器的preHandle()方法或 handler 自身。
* 否则,
*/
boolean applyPreHandle(HttpServletRequest request, HttpServletResponse response) throws Exception {
HandlerInterceptor[] interceptors = getInterceptors();
if (!ObjectUtils.isEmpty(interceptors)) {
for (int i = 0; i < interceptors.length; i++) {
HandlerInterceptor interceptor = interceptors[i];
if (!interceptor.preHandle(request, response, this.handler)) {
triggerAfterCompletion(request, response, null);
return false;
}
this.interceptorIndex = i;
}
}
return true;
}
/*
* 执行已经注册的拦截器 postHandle()方法。
*/
void applyPostHandle(HttpServletRequest request, HttpServletResponse response, ModelAndView mv) throws Exception {
HandlerInterceptor[] interceptors = getInterceptors();
if (!ObjectUtils.isEmpty(interceptors)) {
for (int i = interceptors.length - 1; i >= 0; i--) {
HandlerInterceptor interceptor = interceptors[i];
interceptor.postHandle(request, response, this.handler, mv);
}
}
}
/**
* 这个方法只会执行preHandle()方法已经成功执行并且返回true的拦截器中的postHandle()方法。
*/
void triggerAfterCompletion(HttpServletRequest request, HttpServletResponse response, Exception ex)
throws Exception {
HandlerInterceptor[] interceptors = getInterceptors();
if (!ObjectUtils.isEmpty(interceptors)) {
for (int i = this.interceptorIndex; i >= 0; i--) {
HandlerInterceptor interceptor = interceptors[i];
try {
interceptor.afterCompletion(request, response, this.handler, ex);
}
catch (Throwable ex2) {
logger.error("HandlerInterceptor.afterCompletion threw exception", ex2);
}
}
}
}
以上这篇对handlerexecutionchain类的深入理解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持社区。 |