HandlerMapping 組件HandlerMapping 組件,請求的處理器匹配器,負責(zé)為請求找到合適的
由于 HandlerMapping 組件涉及到的內(nèi)容比較多,考慮到內(nèi)容的排版,所以將這部分內(nèi)容拆分成了四個模塊,依次進行分析: HandlerMapping 組件(二)之 HandlerInterceptor 攔截器在上一篇《HandlerMapping 組件(一)之 AbstractHandlerMapping》文檔中分析了 HandlerMapping 組件的 AbstractHandlerMapping 抽象類,在獲取 HandlerInterceptor
public interface HandlerInterceptor {
/**
* 前置處理,在 {@link HandlerAdapter#handle(HttpServletRequest, HttpServletResponse, Object)} 執(zhí)行之前
*/
default boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
return true;
}
/**
* 后置處理,在 {@link HandlerAdapter#handle(HttpServletRequest, HttpServletResponse, Object)} 執(zhí)行成功之后
*/
default void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
@Nullable ModelAndView modelAndView) throws Exception {
}
/**
* 完成處理,在 {@link HandlerAdapter#handle(HttpServletRequest, HttpServletResponse, Object)} 執(zhí)行之后(無論成功還是失?。? * 條件:執(zhí)行 {@link #preHandle(HttpServletRequest, HttpServletResponse, Object)} 成功的攔截器才會執(zhí)行該方法
*/
default void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
@Nullable Exception ex) throws Exception {
}
}HandlerExecutionChain
構(gòu)造方法public class HandlerExecutionChain {
/**
* 處理器
*/
private final Object handler;
/**
* 攔截器數(shù)組
*/
@Nullable
private HandlerInterceptor[] interceptors;
/**
* 攔截器數(shù)組。
*
* 在實際使用時,會調(diào)用 {@link #getInterceptors()} 方法,初始化到 {@link #interceptors} 中
*/
@Nullable
private List<HandlerInterceptor> interceptorList;
/**
* 已成功執(zhí)行 {@link HandlerInterceptor#preHandle(HttpServletRequest, HttpServletResponse, Object)} 的位置
*
* 在 {@link #applyPostHandle} 和 {@link #triggerAfterCompletion} 方法中需要用到,用于倒序執(zhí)行攔截器的方法
*/
private int interceptorIndex = -1;
public HandlerExecutionChain(Object handler) {
this(handler, (HandlerInterceptor[]) null);
}
public HandlerExecutionChain(Object handler, @Nullable HandlerInterceptor... interceptors) {
if (handler instanceof HandlerExecutionChain) {
HandlerExecutionChain originalChain = (HandlerExecutionChain) handler;
this.handler = originalChain.getHandler();
this.interceptorList = new ArrayList<>();
// 將原始的 HandlerExecutionChain 的 interceptors 復(fù)制到 this.interceptorList 中
CollectionUtils.mergeArrayIntoCollection(originalChain.getInterceptors(), this.interceptorList);
// 將入?yún)⒌?nbsp;interceptors 合并到 this.interceptorList 中
CollectionUtils.mergeArrayIntoCollection(interceptors, this.interceptorList);
} else {
this.handler = handler;
this.interceptors = interceptors;
}
}
}
|
|
|