SpringMVC源码解读之HandlerMapping
概述
对于web开发者,mvc模型是大家再熟悉不过的了,springmvc中,满足条件的请求进入到负责请求分发的dispatcherservlet,dispatcherservlet根据请求url到控制器的映射(handlermapping中保存),handlermapping最终返回handlerexecutionchain,其中包含了具体的处理对象handler(也即我们编程时写的controller)以及一系列的拦截器interceptors,此时dispatcherservlet会根据返回的handlerexecutionchain中的handler找到支持这一处理器类型的适配器(handleradapter),在处理器适配器中最终会去调用控制器的请求响应方法并返回结果视图(modelandview),得到结果视图后,通过render方法完成结果的显示。
handermapping的继承体系:
springmvc在请求到handler处理器的分发这步是通过handlermapping模块解决的.handlermapping 还处理拦截器.
先看看handlermapping的继承树吧
可以大致这样做个分类:
1. 一个接口handlermapping,定义一个api: handlerexecutionchain gethandler(httpservletrequest request) throws exception;
2. 一个基础抽象类:主要是准备上下文环境,提供gethandlerinternal钩子,封装拦截器到handlerexecutionchain
3. 基于注解@controller,@requestmapping的使用
4. 配置文件中直接配置url到 handler的simpleurlhandlermapping
5. 默认实现beannameurlhandlermapping
6. controller子类的映射
看看handlermapping吧,就一个gethandler api 非常简单.
// handlermapping package org.springframework.web.servlet; public interface handlermapping { handlerexecutionchain gethandler(httpservletrequest request) throws exception; }
abstracthandlermapping就没有这么简单了
先看abstracthandlermapping继承的类,实现的接口
package org.springframework.web.servlet.handler; public abstract class abstracthandlermapping extends webapplicationobjectsupport implements handlermapping, ordered { // ... }
webapplicationobjectsupport用于提供上下文applicationcontext和servletcontext.
还有这边的initapplicationcontext方法,在后续经常会使用到.abstracthandlermapping就直接覆写了.
父类里还是实现了applicationcontextaware和servletcontextaware接口,spring概念很统一.
ordered用于集合排序.
再接着看abstracthandlermapping的属性吧
// abstracthandlermapping // order赋了最大值,优先级是最小的 private int order = integer.max_value; // default: same as non-ordered // 默认的handler,这边使用的obejct,子类实现的时候,使用handlermethod,handlerexecutionchain等 private object defaulthandler; // url计算的辅助类 private urlpathhelper urlpathhelper = new urlpathhelper(); // 基于ant进行path匹配,解决如/books/{id}场景 private pathmatcher pathmatcher = new antpathmatcher(); // 拦截器配置:,handlermapping属性设置;,extendinterceptors设置 private final list<object> interceptors = new arraylist<object>(); // 从interceptors中解析得到,直接添加给全部handler private final list<handlerinterceptor> adaptedinterceptors = new arraylist<handlerinterceptor>(); // 使用前需要跟url进行匹配,匹配通过才会使用 private final list<mappedinterceptor> mappedinterceptors = new arraylist<mappedinterceptor>();
看下拦截器的初始化:
// abstracthandlermapping @override protected void initapplicationcontext() throws beansexception { extendinterceptors(this.interceptors); detectmappedinterceptors(this.mappedinterceptors); initinterceptors(); } /** * 提供给子类扩展拦截器,可惜都没有使用 */ protected void extendinterceptors(list<object> interceptors) { } /** * 扫描应用下的mappedinterceptor,并添加到mappedinterceptors */ protected void detectmappedinterceptors(list<mappedinterceptor> mappedinterceptors) { mappedinterceptors.addall( beanfactoryutils.beansoftypeincludingancestors( getapplicationcontext(),mappedinterceptor.class, true, false).values()); } /** * 归集mappedinterceptor,并适配handlerinterceptor和webrequestinterceptor */ protected void initinterceptors() { if (!this.interceptors.isempty()) { for (int i = ; i < this.interceptors.size(); i++) { object interceptor = this.interceptors.get(i); if (interceptor == null) { throw new illegalargumentexception("entry number " + i + " in interceptors array is null"); } if (interceptor instanceof mappedinterceptor) { mappedinterceptors.add((mappedinterceptor) interceptor); } else { adaptedinterceptors.add(adaptinterceptor(interceptor)); } } } } protected handlerinterceptor adaptinterceptor(object interceptor) { if (interceptor instanceof handlerinterceptor) { return (handlerinterceptor) interceptor; } else if (interceptor instanceof webrequestinterceptor) { return new webrequesthandlerinterceptoradapter((webrequestinterceptor) interceptor); } else { throw new illegalargumentexception("interceptor type not supported: " + interceptor.getclass().getname()); } }
然后是gethandler(httpservletrequest request)的实现,这边同时预留gethandlerinternal(httpservletrequest request)给子类实现
// abstracthandlermapping 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 = getapplicationcontext().getbean(handlername); } return gethandlerexecutionchain(handler, request); } protected abstract object gethandlerinternal(httpservletrequest request) throws exception;
最后是封装拦截器到handlerexecutionchain
adaptedinterceptors直接添加
mappedinterceptors需要根据url匹配通过后添加
// abstracthandlermapping protected handlerexecutionchain gethandlerexecutionchain(object handler, httpservletrequest request) { handlerexecutionchain chain = (handler instanceof handlerexecutionchain) ? (handlerexecutionchain) handler : new handlerexecutionchain(handler); chain.addinterceptors(getadaptedinterceptors()); string lookuppath = urlpathhelper.getlookuppathforrequest(request); for (mappedinterceptor mappedinterceptor : mappedinterceptors) { if (mappedinterceptor.matches(lookuppath, pathmatcher)) { chain.addinterceptor(mappedinterceptor.getinterceptor()); } } return chain; }
controller子类的映射,这一分支先看类继承
我们来说说,这边每个类主要的职责
1. abstracthandlermapping 准备上下文环境;提供gethandlerinternal钩子;封装拦截器到handlerexecutionchain
2. abstracturlhandlermapping 实现注册handler的方法供子类使用;实现gethandlerinternal,根据子类初始化的配置信息,查找handler
3. abstractdetectingurlhandlermapping 扫描应用下的object,迭代后提供钩子方法determineurlsforhandler由子类决定如何过滤
4. abstractcontrollerurlhandlermapping 实现determineurlsforhandler,添加过滤排除的handler操作(配置文件配置),预留钩子方法buildurlsforhandler给子类实现;同时判断controller的子类
5. controllerbeannamehandlermapping 根据bean name生成url
controllerclassnamehandlermapping根据class name生成url
从abstracturlhandlermapping开始看吧,这边只是大致看下代码,如果需要仔细分析,请移步<springmvc源码解读 - handlermapping - abstracturlhandlermapping系列request分发>
handler的注册
protected void registerhandler(string[] urlpaths, string beanname) throws beansexception, illegalstateexception { } protected void registerhandler(string urlpath, object handler) throws beansexception, illegalstateexception { }
handler的查找
protected object gethandlerinternal(httpservletrequest request) throws exception {} // 根据url查找handler protected object lookuphandler(string urlpath, httpservletrequest request) throws exception {} // 校验handler protected void validatehandler(object handler, httpservletrequest request) throws exception {} // 封装拦截器到handlerexecutionchain protected object buildpathexposinghandler(object rawhandler, string bestmatchingpattern, string pathwithinmapping, map<string, string> uritemplatevariables) {}
abstractdetectingurlhandlermapping,这边一样不展开,具体移步<springmvc源码解读 - handlermapping - abstractdetectingurlhandlermapping系列初始化>
具体做的事情:
1. 通过覆写initapplicationcontext,调用detecthandlers扫描obejct
2. 提供钩子方法determineurlsforhandler给子类根据handler生成url
3. 调用父类的registerhandler进行注册
@override public void initapplicationcontext() throws applicationcontextexception { super.initapplicationcontext(); detecthandlers(); } protected void detecthandlers() throws beansexception { // ... } /** * determine the urls for the given handler bean. * 钩子而已 */ protected abstract string[] determineurlsforhandler(string beanname); abstractcontrollerurlhandlermapping,这边一样不展开,具体移步<springmvc源码解读 - handlermapping - abstractdetectingurlhandlermapping系列初始化>
具体做的事情;
1. 覆写determineurlsforhandler添加剔除部分类的逻辑,通过配置文件配置的excludedclasses和excludedpackages在这边使用
2. 判断是否controller的子类
3. 预留buildurlsforhandler给子类生成url
@override protected string[] determineurlsforhandler(string beanname) { class beanclass = getapplicationcontext().gettype(beanname); if (iseligibleformapping(beanname, beanclass)) { return buildurlsforhandler(beanname, beanclass); } else { return null; } } protected boolean iseligibleformapping(string beanname, class beanclass) {} protected boolean iscontrollertype(class beanclass) {} protected abstract string[] buildurlsforhandler(string beanname, class beanclass); controllerbeannamehandlermapping和controllerclassnamehandlermapping 直接看源码吧,或者移步<springmvc源码解读 - handlermapping - abstractdetectingurlhandlermapping系列初始化>
配置文件中直接配置url到 handler的simpleurlhandlermapping,就是使用registerhandlers注册配置文档中的handler,直接看代码或者移步<springmvc源码解读 - handlermapping - simpleurlhandlermapping初始化>吧
beannameurlhandlermapping 实现determineurlsforhandler生成url,直接看代码或者移步<springmvc源码解读 - handlermapping - abstractdetectingurlhandlermapping系列初始化>吧
基于注解@controller,@requestmapping的使用
最难吭的骨头
先看类继承吧
说下各个类的职责吧,具体的分析还是移步下面的文章
<springmvc源码解读 - handlermapping - requestmappinghandlermapping初始化>
<springmvc源码解读 - handlermapping - requestmappinghandlermapping请求分发>
1. abstracthandlermethodmaping 定义初始化流程,请求时如何映射
初始化:
1.1.1 扫描应用下的object
1.1.2 预留ishandler钩子方法给子类判断object是否handler
1.1.3 迭代扫描每一个handler,找出符合要求的方法,这边判断依然是留给子类实现getmappingformethod
1.1.4 注册查找到的处理器,需要确保一个匹配条件requestmappinginfo只能映射到一个handler
1.1.5 根据匹配条件获取url,同样的只是定义流程,具体的算法留给子类实现getmappingpathpatterns
请求request分发处理:
1.2.1 直接字符串匹配的方式,查找handler
1.2.2 匹配条件查找,这边具体的算法交由子类处理getmatchingmapping
1.2.3 排序并获取最佳匹配handler,这边的排序方式还是子类处理getmappingconmparator
1.2.4 分别封装匹配到和未匹配到handler的情况
2. requestmappinginfohandlermapping使用requestmappinginfo实现匹配条件,requestmappinginfo的初始化留给子类
2.1 根据requestmappinginfo生成url ->getmappingpathpatterns
2.2 使用匹配条件查找handler -> getmatchingmapping
2.3 完成比较器算法 -> getmappingcomparator
2.4 覆写handlematch,缓存n多信息到request
注册pattern,最佳匹配的pattern,url中解析出来的参数,url中解析出来的多值参数,mediatype
2.1.5 覆写handlernomatch,最后的挣扎,再尝试匹配一次
3. requestmappinghandlermapping 根据注解@controller @requestmapping生成requestmappinginfo,并校验ishandler
3.1 覆写afterpropertiesset,添加文件后缀判断
3.2 实现ishandler,类上有@controller @requestmapping其中一个注解就对
3.3 解析注解内容,生产requestmappinginfo实例
下一篇: PHP网站自动化配置的实现方法(必看)
推荐阅读
-
SpringMVC源码解读之HandlerMapping - AbstractUrlHandlerMapping系列request分发
-
SpringMVC源码解读之HandlerMapping
-
SpringMVC源码解读之HandlerMapping
-
SpringMVC源码解读之 HandlerMapping - AbstractDetectingUrlHandlerMapping系列初始化
-
SpringMVC源码解读之HandlerMapping - AbstractUrlHandlerMapping系列request分发
-
SpringMVC源码解析之消息转换器HttpMessageConverter
-
PHP网页游戏学习之Xnova(ogame)源码解读(一)_PHP教程
-
PHP网页游戏学习之Xnova(ogame)源码解读(八)
-
PHP网页游戏学习之Xnova(ogame)源码解读(七)
-
PHP网页游戏学习之Xnova(ogame)源码解读(二)_PHP教程