SpringMVC【二】HandlerMapping
- 版本说明:5.1.3-RELEASE
上节我们对DispatcherServlet如何串起请求的流程进行了梳理,本文将针对其中的HandlerMapping进行研究。
HandlerMapping
我们知道HandlerMapping是一个接口,只有一个getHandler(HttpServletRequest request)接口方法需要子类实现,返回HandlerExecutionChain对象,HandlerExecutionChain具体包含Handler对象以及Interceptors集合;如下是具体代码:
public interface HandlerMapping { /**省略部分常量**/ @Nullable HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception;}-----------------------------------------分割线------------------------------------public class HandlerExecutionChain { /**handler对象**/ private final Object handler; @Nullable private HandlerInterceptor[] interceptors; /**阻拦器集合**/ @Nullable private List<HandlerInterceptor> interceptorList;}
我们再通过如下类图理解HandlerMapping的继承实现结构:
HandlerMapping
AbstractHandlerMapping
我们先看HandlerMapping的笼统子类AbstractHandlerMapping是如何实现getHandler接口的:
getHandler
笼统方法以及包装过程
那么getHandlerInternal具体是如何实现的呢,我们来看看AbstractHandlerMapping的两个子类;
AbstractHandlerMapping子类
AbstractHandlerMapping子类AbstractHandlerMethodMapping
获取HandlerMethod过程
AbstractHandlerMethodMapping实现getHandlerInternal方法
getHandlerInternal
我们一起来梳理一下获取getHandlerInternal的过程:
1.先根据请求获取lookupPath
2.根据lookupPath以及request调用lookupHandlerMethod
3.Match是笼统类的一个内部类,用于记录Mapping跟HandlerMethod对应关系
4.具体的能否匹配在调用addMatchingMappings时由子类实现getMatchingMapping方法来确定
5.假如匹配的match不唯一,由子类利用getMappingComparator方法返回comparator来决定。
6.返回bestMatch.handlerMethod
HandlerMethod初始化过程
我们通过以上代码理解到如何HandlerMethod,那么mappingRegistry是如何初始化的呢?
AbstractHandlerMethodMapping实现了InitializingBean接口,初始化时会调用afterPropertiesSet方法,此方法便是入口,以下是代码流程:
@Overridepublic void afterPropertiesSet() {/**1.调用初始化方法**/initHandlerMethods();}/**初始化HandlerMethod**/protected void initHandlerMethods() {/**2.getCandidateBeanNames获取候选的BeanName**//**遍历所有候选beanName**/for (String beanName : getCandidateBeanNames()) { if (!beanName.startsWith(SCOPED_TARGET_NAME_PREFIX)) { /**3.解决候选的Beans**/ processCandidateBean(beanName); }}handlerMethodsInitialized(getHandlerMethods());}/**获取候选的BeanName**/protected String[] getCandidateBeanNames() {return (this.detectHandlerMethodsInAncestorContexts ? BeanFactoryUtils.beanNamesForTypeIncludingAncestors(obtainApplicationContext(), Object.class) : obtainApplicationContext().getBeanNamesForType(Object.class));}/**解决候选的Beans**/protected void processCandidateBean(String beanName) {Class<?> beanType = null;try { beanType = obtainApplicationContext().getType(beanName);}catch (Throwable ex) { if (logger.isTraceEnabled()) { logger.trace("Could not resolve type for bean '" + beanName + "'", ex); }} /**4.isHandler笼统方法由子类实现**/if (beanType != null && isHandler(beanType)) { /**5.探测HandlerMethod**/ detectHandlerMethods(beanName);}}/**笼统方法由子类实现,被Controller或者RequestMapping注解标注**/protected abstract boolean isHandler(Class<?> beanType);/**探测HandlerMethod**/ protected void detectHandlerMethods(Object handler) {/**获取handler的类类型**/Class<?> handlerType = (handler instanceof String ? obtainApplicationContext().getType((String) handler) : handler.getClass());if (handlerType != null) { /**获取实际类类型,handlerType有可能是由CGLIB代理商生成的子类**/ Class<?> userType = ClassUtils.getUserClass(handlerType);/**反射获取userType类的方法以及T,T泛型由子类指定**/ Map<Method, T> methods = MethodIntrospector.selectMethods(userType, (MethodIntrospector.MetadataLookup<T>) method -> { try { /**6.笼统方法,由子类实现,返回该方法的Mapping信息**/ return getMappingForMethod(method, userType); } catch (Throwable ex) { throw new IllegalStateException("Invalid mapping on handler class [" + userType.getName() + "]: " + method, ex); } }); if (logger.isTraceEnabled()) { logger.trace(formatMappings(userType, methods)); } methods.forEach((method, mapping) -> { Method invocableMethod = AopUtils.selectInvocableMethod(method, userType); /**7.注册Handler,method,mapping到MappingRegistry**/ registerHandlerMethod(handler, invocableMethod, mapping); });}}/**注册Handler,method,mapping到MappingRegistry**/protected void registerHandlerMethod(Object handler, Method method, T mapping) { this.mappingRegistry.register(mapping, handler, method);}
image.png
我们梳理一下注册的流程:
1.初始化时调用initHandlerMethods方法
2.获取候选beanNames
3.解决候选beanName
4.由子类isHandler方法完成能否handler判断
5.探测HandlerMethods
6.由子类返回getMappingForMethod的Mapping信息
7.注册Handler,method,mapping到MappingRegistry
AbstractHandlerMethodMapping继承关系如下:
AbstractHandlerMethodMapping子类
RequestMappingHandlerMapping中isHandler方法实现
@Overrideprotected boolean isHandler(Class<?> beanType) { return (AnnotatedElementUtils.hasAnnotation(beanType, Controller.class) || AnnotatedElementUtils.hasAnnotation(beanType, RequestMapping.class));}
RequestMappingHandlerMapping中根据一个类能否有@Controller或者@RequestMapping注解来判断能否是Handler
而AbstractHandlerMethodMapping的另一个子类RequestMappingInfoHandlerMapping则指定了泛型RequestMappingInfo,前文中所讲的T的真身便是RequestMappingInfo了,它具体就是解析了@RequestMapping注解中的值。
// @RequestMapping 中的信息private final String name;// @RequestMapping 中 value|path 的解析器,private final PatternsRequestCondition patternsCondition;// @RequestMapping 中 RequestMethod 的解析器private final RequestMethodsRequestCondition methodsCondition;// @RequestMapping 中 param 的解析器private final ParamsRequestCondition paramsCondition;// @RequestMapping 中 headers 的解析器private final HeadersRequestCondition headersCondition;// @RequestMapping 中 consumes 的解析器private final ConsumesRequestCondition consumesCondition;// @RequestMapping 中 produces 的解析器private final ProducesRequestCondition producesCondition;// RequestCondition 的 holderprivate final RequestConditionHolder customConditionHolder;
AbstractHandlerMapping子类AbstractUrlHandlerMapping
我们知道AbstractHandlerMapping有两个关键的子类一个是AbstractMethodHandlerMapping,而另一个则是AbstractUrlHandlerMapping,同样的先看getHandlerInternal实现
获取Handler过程
getHandlerInternal
lookupHandler
buildPathExposingHandler
我们梳理一下获取Handler的过程:
1.调用lookupHandler
2.根据urlPath获取,不为空则构建Handler返回
3.为空则根据pattern获取,获取到最匹配的则构建返回
4.假如没有获取到则解决默认Handler,如:RootHandler,DefaultHandler等
5.返回Handler
Handler初始化过程
同样的我们理解清楚获取的过程以后,一起来学习一下初始化Handler的过程,我们没有找到初始化相关的initXX方法,当时发现了registerHandler方法,我们大胆的猜想,它可能是有子类初始化时调用的,我们先看这个方法具体的内容:
registerHandler
AbstractUrlHandlerMapping继承关系如下
AbstractUrlHandlerMapping继承关系
分支子类AbstractDetectingUrlHandlerMapping
先看AbstractDetectingUrlHandlerMapping 初始化过程
initApplicationContext
detectHandlers
determineUrlsForHandler
AbstractDetectingUrlHandlerMapping子类BeanNameUrlHandlerMapping实现determineUrlsForHandler方法
BeanNameUrlHandlerMapping
分支子类SimpleUrlHandlerMapping
initApplicationContext
registerHandlers
总结
1.理解HandlerMapping的核心子类AbstractHandlerMapping
2.其次理解HandlerExecutionChain的结构Handler对象+ Interceptors
3.理解AbstractHandlerMapping 的两个分支子类AbstractHandlerMethodMapping,AbstractUrlHandlerMapping
4.清楚获取Handler 以及 注册 Handler的过程
1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 本站资源售价只是摆设,本站源码仅提供给会员学习使用!
7. 如遇到加密压缩包,请使用360解压,如遇到无法解压的请联系管理员
开心源码网 » SpringMVC【二】HandlerMapping