行封装处理,跟进SimpleUrlHandlerMapping的getHandler方法:
public final HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
// 根据request获取对应的handler
Object handler = getHandlerInternal(request);
if (handler == null) {
// 如果没有则使用默认的handler
handler = getDefaultHandler();
}
if (handler == null) {
return null;
}
if (handler instanceof String) {
String handlerName = (String) handler;
handler = getApplicationContext().getBean(handlerName);
}
return getHandlerExecutionChain(handler, request);
}
上面源码应该很清晰,根据request获取对应的Handler,如果没有的话则使用默认的,当查找到的controller为String类型时,就意味着返回的是配置的bean名称,需要根据bean名称查找对应的bean,最后通过getHandlerExecutionChain方法对返回的Handler进行封装,以满足返回类型的匹配。
接着跟进getHandlerInternal方法源码来看看怎样根据request查找对应的Handler:
protected Object getHandlerInternal(HttpServletRequest request) throws Exception {
// 获取用于匹配的url有效路径
String lookupPath = getUrlPathHelper().getLookupPathForRequest(request);
// 根据上面的路径寻找handler
Object handler = lookupHandler(lookupPath, request);
if (handler == null) {
// We need to care for the default handler directly, since we need to
// expose the PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE for it as well.
Object rawHandler = null;
if ("/".equals(lookupPath)) {
// 如果请求的路径是“/”,则使用RootHandler进行处理
rawHandler = getRootHandler();
}
if (rawHandler == null) {
rawHandler = getDefaultHandler();
}
if (rawHandler != null) {
// 根据beanName获取对应的bean
if (rawHandler instanceof String) {
String handlerName = (String) rawHandler;
rawHandler = getApplicationContext().getBean(handlerName);
}
validateHandler(rawHandler, request);
handler = buildPathExposingHandler(rawHandler, lookupPath, lookupPath, null);
}
}
if (handler != null && logger.isDebugEnabled()) {
logger.debug("Mapping [" + lookupPath + "] to " + handler);
}
else if (handler == null && logger.isTraceEnabled()) {
logger.trace("No handler mapping found for [" + lookupPath + "]");
}
return handler;
}
protected Object lookupHandler(String urlPath, HttpServletRequest request) throws Exception {
// 直接匹配情况的处理
Object handler = this.handlerMap.get(urlPath);
if (handler != null) {
// Bean name or resolve