SpringMVC源码之Controller查找原理
摘要
- 本文从源码层面简单讲解SpringMVC的处理器映射环节,也就是查找Controller详细过程。
SpringMVC请求流程

- Controller查找在上图中对应的步骤1至2的过程
SpringMVC初始化过程
理解初始化过程之前,先认识两个类
- RequestMappingInfo类,对RequestMapping注解封装。里面包含http请求头的相关信息。如uri、method、params、header等参数。一个对象对应一个RequestMapping注解
- HandlerMethod类,是对Controller的处理请求方法的封装。里面包含了该方法所属的bean对象、该方法对应的method对象、该方法的参数等。

- 上图是RequestMappingHandlerMapping的继承关系。在SpringMVC初始化的时候,首先执行RequestMappingHandlerMapping中的afterPropertiesSet方法,然后会进入AbstractHandlerMethodMapping的afterPropertiesSet方法(line:93),这个方法会进入当前类的initHandlerMethods方法(line:103)。这个方法的职责便是从applicationContext中扫描beans,然后从bean中查找并注册处理器方法,代码如下。
protected void initHandlerMethods() {
if (logger.isDebugEnabled()) {
logger.debug("Looking for request mappings in application context: " + getApplicationContext());
}
//获取applicationContext中所有的bean name
String[] beanNames = (this.detectHandlerMethodsInAncestorContexts ?
BeanFactoryUtils.beanNamesForTypeIncludingAncestors(getApplicationContext(), Object.class) :
getApplicationContext().getBeanNamesForType(Object.class));
//遍历beanName数组
for (String beanName : beanNames) {
//isHandler会根据bean来判断bean定义中是否带有Controller注解或RequestMapping注解
if (isHandler(getApplicationContext().getType(beanName))){
detectHandlerMethods(beanName);
}
}
handlerMethodsInitialized(getHandlerMethods());
}
- isHandler方法其实很简单,如下
@Override
protected boolean isHandler(Class<?> beanType) {
return ((AnnotationUtils.findAnnotation(beanType, Controller.class) != null) ||
(AnnotationUtils.findAnnotation(beanType, RequestMapping.class) != null));
}
- 就是判断当前bean定义是否带有Controlller注解或RequestMapping注解,看了这里逻辑可能会想如果只有RequestMapping会生效吗?答案是不会的,因为在这种情况下Spring初始化的时候不会把该类注册为Spring bean,遍历beanNames时不会遍历到这个类,所以这里把Controller换成Compoent注解也是可以,不过一般不会这么做。当确定bean为handlers后,便会从该bean中查找出具体的handler方法(也就是我们通常定义的Controller类下的具体定义的请求处理方法),查找代码如下
protected void detectHandlerMethods(final Object handler) {
//获取到当前Controller bean的class对象
Class<?> handlerType = (handler instanceof String) ?
getApplicationContext().getType((String) handler) : handler.getClass();
//同上,也是该Controller bean的class对象
final Class<?> userType = ClassUtils.getUserClass(handlerType);
//获取当前bean的所有handler method。这里查找的依据便是根据method定义是否带有RequestMapping注解。如果有根据注解创建RequestMappingInfo对象
Set<Method> methods = HandlerMethodSelector.selectMethods(userType, new MethodFilter() {
public boolean matches(Method method) {
return getMappingForMethod(method, userType) != null;
}
});
//遍历并注册当前bean的所有handler method
for (Method method : methods) {
T mapping = getMappingForMethod(method, userType);
//注册handler method,进入以下方法
registerHandlerMethod(handler, method, mapping);
}
}
- 以上代码有两个地方有调用了getMappingForMethod方法
protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) {
RequestMappingInfo info = null;
//获取method的@RequestMapping注解
RequestMapping methodAnnotation = AnnotationUtils.findAnnotation(method, RequestMapping.class);
if (methodAnnotation != null) {
RequestCondition<?> methodCondition = getCustomMethodCondition(method);
info = createRequestMappingInfo(methodAnnotation, methodCondition);
//获取method所属bean的@RequtestMapping注解
RequestMapping typeAnnotation = AnnotationUtils.findAnnotation(handlerType, RequestMapping.class);
if (typeAnnotation != null) {
RequestCondition<?> typeCondition = getCustomTypeCondition(handlerType);
//合并两个@RequestMapping注解
info = createRequestMappingInfo(typeAnnotation, typeCondition).combine(info);
}
}
return info;
}
- 这个方法的作用就是根据handler method方法创建RequestMappingInfo对象。首先判断该mehtod是否含有RequestMpping注解。如果有则直接根据该注解的内容创建RequestMappingInfo对象。创建以后判断当前method所属的bean是否也含有RequestMapping注解。如果含有该注解则会根据该类上的注解创建一个RequestMappingInfo对象。然后在合并method上的RequestMappingInfo对象,最后返回合并后的对象。现在回过去看detectHandlerMethods方法,有两处调用了getMappingForMethod方法,个人觉得这里是可以优化的,在第一处判断method时否为handler时,创建的RequestMappingInfo对象可以保存起来,直接拿来后面使用,就少了一次创建RequestMappingInfo对象的过程。然后紧接着进入registerHandlerMehtod方法,如下
protected void registerHandlerMethod(Object handler, Method method, T mapping) {
//创建HandlerMethod
HandlerMethod newHandlerMethod = createHandlerMethod(handler, method);
HandlerMethod oldHandlerMethod = handlerMethods.get(mapping);
//检查配置是否存在歧义性
if (oldHandlerMethod != null && !oldHandlerMethod.equals(newHandlerMethod)) {
throw new IllegalStateException("Ambiguous mapping found. Cannot map '" + newHandlerMethod.getBean()
+ "' bean method \n" + newHandlerMethod + "\nto " + mapping + ": There is already '"
+ oldHandlerMethod.getBean() + "' bean method\n" + oldHandlerMethod + " mapped.");
}
this.handlerMethods.put(mapping, newHandlerMethod);
if (logger.isInfoEnabled()) {
logger.info("Mapped \"" + mapping + "\" onto " + newHandlerMethod);
}
//获取@RequestMapping注解的value,然后添加value->RequestMappingInfo映射记录至urlMap中
Set<String> patterns = getMappingPathPatterns(mapping);
for (String pattern : patterns) {
if (!getPathMatcher().isPattern(pattern)) {
this.urlMap.add(pattern, mapping);
}
}
}
- 这里T的类型是RequestMappingInfo。这个对象就是封装的具体Controller下的方法的RequestMapping注解的相关信息。一个RequestMapping注解对应一个RequestMappingInfo对象。HandlerMethod和RequestMappingInfo类似,是对Controlelr下具体处理方法的封装。先看方法的第一行,根据handler和mehthod创建HandlerMethod对象。第二行通过handlerMethods map来获取当前mapping对应的HandlerMethod。然后判断是否存在相同的RequestMapping配置。如下这种配置就会导致此处抛
Invocation of init method failed; nested exception is java.lang.IllegalStateException: Ambiguous mapping found. Cannot map...
异常
@Controller
@RequestMapping("/AmbiguousTest")
public class AmbiguousTestController {
@RequestMapping(value = "/test1")
@ResponseBody
public String test1(){
return "method test1";
}
@RequestMapping(value = "/test1")
@ResponseBody
public String test2(){
return "method test2";
}
}
- 在SpingMVC启动(初始化)阶段检查RequestMapping配置是否有歧义,这是其中一处检查歧义的(后面还会提到一个在运行时检查歧义性的地方)。然后确认配置正常以后会把该RequestMappingInfo和HandlerMethod对象添加至handlerMethods(LinkedHashMap<RequestMappingInfo,HandlerMethod>)中,静接着把RequestMapping注解的value和ReuqestMappingInfo对象添加至urlMap中。
registerHandlerMethod方法简单总结
该方法的主要有3个职责
- 检查RequestMapping注解配置是否有歧义。
- 构建RequestMappingInfo到HandlerMethod的映射map。该map便是AbstractHandlerMethodMapping的成员变量handlerMethods。LinkedHashMap<RequestMappingInfo,HandlerMethod>。
- 构建AbstractHandlerMethodMapping的成员变量urlMap,MultiValueMap<String,RequestMappingInfo>。这个数据结构可以把它理解成Map<String,List>。其中String类型的key存放的是处理方法上RequestMapping注解的value。就是具体的uri
先有如下Controller
@Controller
@RequestMapping("/UrlMap")
public class UrlMapController {
@RequestMapping(value = "/test1", method = RequestMethod.GET)
@ResponseBody
public String test1(){
return "method test1";
}
@RequestMapping(value = "/test1")
@ResponseBody
public String test2(){
return "method test2";
}
@RequestMapping(value = "/test3")
@ResponseBody
public String test3(){
return "method test3";
}
}
- 初始化完成后,对应AbstractHandlerMethodMapping的urlMap的结构如下

- 以上便是SpringMVC初始化的主要过程
查找过程
- 为了理解查找流程,带着一个问题来看,现有如下Controller
@Controller
@RequestMapping("/LookupTest")
public class LookupTestController {
@RequestMapping(value = "/test1", method = RequestMethod.GET)
@ResponseBody
public String test1(){
return "method test1";
}
@RequestMapping(value = "/test1", headers = "Referer=https://www.baidu.com")
@ResponseBody
public String test2(){
return "method test2";
}
@RequestMapping(value = "/test1", params = "id=1")
@ResponseBody
public String test3(){
return "method test3";
}
@RequestMapping(value = "/*")
@ResponseBody
public String test4(){
return "method test4";
}
}
- 有如下请求

- 这个请求会进入哪一个方法?
- web容器(Tomcat、jetty)接收请求后,交给DispatcherServlet处理。FrameworkServlet调用对应请求方法(eg:get调用doGet),然后调用processRequest方法。进入processRequest方法后,一系列处理后,在line:936进入doService方法。然后在Line856进入doDispatch方法。在line:896获取当前请求的处理器handler。然后进入AbstractHandlerMethodMapping的lookupHandlerMethod方法。代码如下
protected HandlerMethod lookupHandlerMethod(String lookupPath, HttpServletRequest request) throws Exception {
List<Match> matches = new ArrayList<Match>();
//根据uri获取直接匹配的RequestMappingInfos
List<T> directPathMatches = this.urlMap.get(lookupPath);
if (directPathMatches != null) {
addMatchingMappings(directPathMatches, matches, request);
}
//不存在直接匹配的RequetMappingInfo,遍历所有RequestMappingInfo
if (matches.isEmpty()) {
// No choice but to go through all mappings
addMatchingMappings(this.handlerMethods.keySet(), matches, request);
}
//获取最佳匹配的RequestMappingInfo对应的HandlerMethod
if (!matches.isEmpty()) {
Comparator<Match> comparator = new MatchComparator(getMappingComparator(request));
Collections.sort(matches, comparator);
if (logger.isTraceEnabled()) {
logger.trace("Found " + matches.size() + " matching mapping(s) for [" + lookupPath + "] : " + matches);
}
//再一次检查配置的歧义性
Match bestMatch = matches.get(0);
if (matches.size() > 1) {
Match secondBestMatch = matches.get(1);
if (comparator.compare(bestMatch, secondBestMatch) == 0) {
Method m1 = bestMatch.handlerMethod.getMethod();
Method m2 = secondBestMatch.handlerMethod.getMethod();
throw new IllegalStateException(
"Ambiguous handler methods mapped for HTTP path '" + request.getRequestURL() + "': {" +
m1 + ", " + m2 + "}");
}
}
handleMatch(bestMatch.mapping, lookupPath, request);
return bestMatch.handlerMethod;
}
else {
return handleNoMatch(handlerMethods.keySet(), lookupPath, request);
}
}
进入lookupHandlerMethod方法,其中lookupPath="/LookupTest/test1",根据lookupPath,也就是请求的uri。直接查找urlMap,获取直接匹配的RequestMappingInfo list。这里会匹配到3个RequestMappingInfo。如下

然后进入addMatchingMappings方法
private void addMatchingMappings(Collection<T> mappings, List<Match> matches, HttpServletRequest request) {
for (T mapping : mappings) {
T match = getMatchingMapping(mapping, request);
if (match != null) {
matches.add(new Match(match, handlerMethods.get(mapping)));
}
}
}
- 这个方法的职责是遍历当前请求的uri和mappings中的RequestMappingInfo能否匹配上,如果能匹配上,创建一个相同的RequestMappingInfo对象。再获取RequestMappingInfo对应的handlerMethod。然后创建一个Match对象添加至matches list中。执行完addMatchingMappings方法,回到lookupHandlerMethod。这时候matches还有3个能匹配上的RequestMappingInfo对象。接下来的处理便是对matchers列表进行排序,然后获取列表的第一个元素作为最佳匹配。返回Match的HandlerMethod。这里进入RequestMappingInfo的compareTo方法,看一下具体的排序逻辑。代码如下
public int compareTo(RequestMappingInfo other, HttpServletRequest request) {
int result = patternsCondition.compareTo(other.getPatternsCondition(), request);
if (result != 0) {
return result;
}
result = paramsCondition.compareTo(other.getParamsCondition(), request);
if (result != 0) {
return result;
}
result = headersCondition.compareTo(other.getHeadersCondition(), request);
if (result != 0) {
return result;
}
result = consumesCondition.compareTo(other.getConsumesCondition(), request);
if (result != 0) {
return result;
}
result = producesCondition.compareTo(other.getProducesCondition(), request);
if (result != 0) {
return result;
}
result = methodsCondition.compareTo(other.getMethodsCondition(), request);
if (result != 0) {
return result;
}
result = customConditionHolder.compareTo(other.customConditionHolder, request);
if (result != 0) {
return result;
}
return 0;
}
- 代码里可以看出,匹配的先后顺序是value>params>headers>consumes>produces>methods>custom,看到这里,前面的问题就能轻易得出答案了。在value相同的情况,params更能先匹配。所以那个请求会进入test3()方法。再回到lookupHandlerMethod,在找到HandlerMethod。SpringMVC还会这里再一次检查配置的歧义性,这里检查的原理是通过比较匹配度最高的两个RequestMappingInfo进行比较。此处可能会有疑问在初始化SpringMVC有检查配置的歧义性,这里为什么还会检查一次。假如现在Controller中有如下两个方法,以下配置是能通过初始化歧义性检查的。
@RequestMapping(value = "/test5", method = {RequestMethod.GET, RequestMethod.POST})
@ResponseBody
public String test5(){
return "method test5";
}
@RequestMapping(value = "/test5", method = {RequestMethod.GET, RequestMethod.DELETE})
@ResponseBody
public String test6(){
return "method test6";
}
- 现在执行 http://localhost:8080/SpringMVC-Demo/LookupTest/test5 请求,便会在lookupHandlerMethod方法中抛
java.lang.IllegalStateException: Ambiguous handler methods mapped for HTTP path 'http://localhost:8080/SpringMVC-Demo/LookupTest/test5'异常。这里抛该异常是因为RequestMethodsRequestCondition的compareTo方法是比较的method数。代码如下
public int compareTo(RequestMethodsRequestCondition other, HttpServletRequest request) {
return other.methods.size() - this.methods.size();
}
- 什么时候匹配通配符?当通过urlMap获取不到直接匹配value的RequestMappingInfo时才会走通配符匹配进入addMatchingMappings方法。
总结
- 解析所使用代码已上传至github,https://github.com/wycm/SpringMVC-Demo
- 以上源码是基于SpringMVC 3.2.2.RELEASE版本。以上便是SpringMVC请求查找的主要过程,希望对大家有帮助。本文可能有错误,希望读者能够指出来。
版权声明
作者:wycm
出处:https://www.cnblogs.com/w-y-c-m/p/8416630.html
您的支持是对博主最大的鼓励,感谢您的认真阅读。
本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
SpringMVC源码之Controller查找原理的更多相关文章
- SpringMVC源码分析6:SpringMVC的视图解析原理
title: SpringMVC源码分析6:SpringMVC的视图解析原理 date: 2018-06-07 11:03:19 tags: - SpringMVC categories: - 后端 ...
- springMVC源码分析--异常处理机制HandlerExceptionResolver执行原理(二)
上一篇博客springMVC源码分析--异常处理机制HandlerExceptionResolver简单示例(一)中我们简单地实现了一个异常处理实例,接下来我们要介绍一下HandlerExceptio ...
- SpringMVC源码阅读:定位Controller
1.前言 SpringMVC是目前J2EE平台的主流Web框架,不熟悉的园友可以看SpringMVC源码阅读入门,它交代了SpringMVC的基础知识和源码阅读的技巧 本文将通过源码分析,弄清楚Spr ...
- SpringMVC源码阅读:Controller中参数解析
1.前言 SpringMVC是目前J2EE平台的主流Web框架,不熟悉的园友可以看SpringMVC源码阅读入门,它交代了SpringMVC的基础知识和源码阅读的技巧 本文将通过源码(基于Spring ...
- springMVC源码分析--HandlerMapping(一)
HandlerMapping的工作就是为每个请求找到合适的请求找到一个处理器handler,其实现机制简单来说就是维持了一个url到Controller关系的Map结构,其提供的实际功能也是根据req ...
- SpringMVC源码阅读:属性编辑器、数据绑定
1.前言 SpringMVC是目前J2EE平台的主流Web框架,不熟悉的园友可以看SpringMVC源码阅读入门,它交代了SpringMVC的基础知识和源码阅读的技巧 本文将通过源码(基于Spring ...
- 框架-springmvc源码分析(一)
框架-springmvc源码分析(一) 参考: http://www.cnblogs.com/heavenyes/p/3905844.html#a1 https://www.cnblogs.com/B ...
- springmvc源码分析系列-请求处理流程
接上一篇-springmvc源码分析开头片 上一节主要说了一下springmvc与struts2的作为MVC中的C(controller)控制层的一些区别及两者在作为控制层方面的一些优缺点.今天就结合 ...
- springmvc源码学习
1.springmvc运行流程 流程图是直接在百度图片中找的一张 >.前台发送请求,请求会首先通过DispatcherServlet进行url的匹配;如果匹配不到,看是否配置<mvc: ...
随机推荐
- d3 画地图终极自适应大小方案
d3,v4以前用d3画地图的时候,为了让地图差不多正好画在容器的上下左右正中间,不得不慢慢的这样调: const projection = d3.geoMercator() .center([108. ...
- Linux ssh双向免密认证
一.实现原理 使用一种被称为"公私钥"认证的方式来进行ssh登录."公私钥"认证方式简单的解释是: 首先在客户端上创建一对公私钥(公钥文件:~/.ssh/id_ ...
- NPOI操作Excel 踩坑记
1 读取Excel并修改单元格 a.一定不能一边读数据,一边修改单元格,否则读出来的数据可能不准 b.注意写文件的模式,不然修改后的文件,打开会报错. c.清空单元格的数据,可以调用SetCellTy ...
- Gym 101612C Consonant Fencity
原题传送门 题意:给定一个只含小写字母的字符串,假设aeiouyw为元音字母,现在要把一些字母变为大写,要求相同字母的大小写必须相同,统计变化后的字符串中有多少对相邻.同为辅音字母且大小写不一样的字符 ...
- CTF---Web入门第十六题 天下武功唯快不破
天下武功唯快不破分值:10 来源: 北邮天枢战队 难度:易 参与人数:10787人 Get Flag:2264人 答题人数:3373人 解题通过率:67% 看看响应头 格式:CTF{ } 解题链接: ...
- BZOJ:1443: [JSOI2009]游戏Game
原题链接:http://www.lydsy.com/JudgeOnline/problem.php?id=1443 反正不看题解我是完全想不出系列…… 先把棋盘黑白染色,也就是同一对角线上颜色相同,使 ...
- 强连通分量&hdu_1269&Codeforce 369D
强连通分量 标签: 图论 算法介绍 还记得割点割边算法吗.回顾一下,tarjan算法,dfs过程中记录当前点的时间戳,并通过它的子节点的low值更新它的low,low值是这个点不通过它的父亲节点最远可 ...
- Legal or Not(拓扑排序判环)
http://acm.hdu.edu.cn/showproblem.php?pid=3342 Legal or Not Time Limit: 2000/1000 MS (Java/Others) ...
- SpringMVC框架学习笔记(5)——数据处理
1.提交数据的处理 a)提交的域名称和参数名称一致 http://localhost:8080/foward/hello.do?name=zhangsan 处理方法 @RequestMapping(v ...
- mitm6:通过IPv6攻破IPv4网络
一.前言 虽然IPv6正在互联网上逐步推广,但在内部网络环境中使用IPv6的公司依然非常稀少.然而,大多数公司并不知道,即使他们没有主动去使用IPv6,但从Windows Vista以来,所有的Win ...
