第2步处理方法:
//遍历所有的映射器,直到找到能够配对该请求的一个映射器,
// 在映射器内部配对到对应的Handler,最终生成HandlerExecutionChain对象并返回
protected HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
if (this.handlerMappings != null) {
for (HandlerMapping hm : this.handlerMappings) {
if (logger.isTraceEnabled()) {
logger.trace(
"Testing handler map [" + hm + "] in DispatcherServlet with name '" + getServletName() + "'");
}
HandlerExecutionChain handler = hm.getHandler(request);
if (handler != null) {
return handler;
}
}
}
return null;
}
//this.handlerMappings在容器初始化时已经生成
//主要看下:HandlerExecutionChain handler = hm.getHandler(request);
getHandler在HandlerMapping接口中
public interface HandlerMapping{
HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception;
}
HandlerMapping接口中getHandler实现类如下:
AbstractHandlerMapping类中实现getHandler方法:
public final HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
//抽象类的抽象方法,匹配对象请求的Handler对象,具体实现逻辑看子类
Object handler = getHandlerInternal(request);
if (handler == null) {
handler = getDefaultHandler();
}
if (handler == null) {
return null;
}
// Bean name or resolved handler?
if (handler instanceof String) {
//如果匹配的Handler对象只是字符串,则以字符串为id。例如容器中得到对象的bean
String handlerName = (String) handler;
handler = obtainApplicationContext().getBean(handlerName);
}
//将匹配的拦截器和Handler对象全部都包装到HandlerExecutionChain对象中
HandlerExecutionChain executionChain = getHandlerExecutionChain(handler, request);
if (CorsUtils.isCorsRequest(request)) {
CorsConfiguration globalConfig = this.globalCorsConfigSource.getCorsConfiguration(request);
CorsConfiguration handlerConfig = getCorsConfiguration(handler, request);
CorsConfiguration config = (globalConfig != null ? globalConfig.combine(handlerConfig) : handlerConfig);
executionChain = getCorsHandlerExecutionChain(request, executionChain, config);
}
return executionChain;
}
protected abstract Object getHandlerInternal(HttpServletRequest request) throws Exception;
getHandler里面有两个方法:
2.1.//抽象类的抽象