HandlerMapping接口
HandlerMapping是用来处理请求与handler对象的对应关系的。
HandlerMapping主要包含getHandler这个方法。
HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception;
DispatcherServlet就是通过调用HandlerMapping的getHandler来进行找到request对应的handler的。
AbstractHandlerMapping类
AbstractHandlerMapping是实现HandlerMapping接口的抽象基类。
首先我们来看其中的getHandler方法:
如果不考虑类中的跨域请求的处理。那么我们可以只关注下面两个方法,getHandlerExecutionChain和getHandler。因为getHandler中调用了getHandlerExecutionChain,所以我们先来看一下getHandlerExecutionChain方法。
protected HandlerExecutionChain getHandlerExecutionChain(Object handler, HttpServletRequest request) {
HandlerExecutionChain chain = (handler instanceof HandlerExecutionChain ?
(HandlerExecutionChain) handler : new HandlerExecutionChain(handler));
String lookupPath = this.urlPathHelper.getLookupPathForRequest(request);
for (HandlerInterceptor interceptor : this.adaptedInterceptors) {
if (interceptor instanceof MappedInterceptor) {
MappedInterceptor mappedInterceptor = (MappedInterceptor) interceptor;
if (mappedInterceptor.matches(lookupPath, this.pathMatcher)) {
chain.addInterceptor(mappedInterceptor.getInterceptor());
}
}
else {
chain.addInterceptor(interceptor);
}
}
return chain;
}
这段代码的意思就是 找到该handler的所有对应MappedInterceptor并将其与handler组合成HandlerExecutionChain,当然还包括所有的非MappedInterceptor类型的HandlerInterceptor。
简言之,就是返回handler所对应的HandlerExecutionChain。
然后我们就来阅读getHandler部分的代码
public final HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
Object handler = getHandlerInternal(request);
if (handler == null) {
handler = getDefaultHandler();
}
if (handler == null) {
return null;
}
// Bean name or resolved handler?
if (handler instanceof String) {
String handlerName = (String) handler;
handler = obtainApplicationContext().getBean(handlerName);
}
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;
}
这段代码的意思就是从request中抽离出handler并调用getHandlerExecutionChain方法组装。(其中getHandlerInternal是一种抽象方法)。
总结
我们可以从上面的代码中总结出整个HandlerMapping的设计思路。
首先[request]由[AbstractHandlerMapping的实现类]处理得到其对应的[handler],接着[handler]由[AbstractHandlerMapping]找到其对应的所有拦截器并包装成[HandlerExecutionChain]返回。