查看: 566|回复: 0

[Java学习] Spring MVC学习笔记之Controller查找(基于Spring4.0.3)

发表于 2018-4-15 08:00:01

0 摘要

本文从源码层面简单讲解SpringMVC的处理器映射环节,也就是查找Controller详细过程

1 SpringMVC请求流程


Controller查找在上图中对应的步骤1至2的过程


SpringMVC详细运行流程图

2 SpringMVC初始化过程

2.1 先认识两个类

1.RequestMappingInfo

封装RequestMapping注解

包含HTTP请求头的相关信息

一个实例对应一个RequestMapping注解

2.HandlerMethod

封装Controller的处理请求方法

包含该方法所属的bean对象、该方法对应的method对象、该方法的参数等

RequestMappingHandlerMapping的继承关系

在SpringMVC初始化的时候

首先执行RequestMappingHandlerMapping的afterPropertiesSet

然后进入AbstractHandlerMethodMapping的afterPropertiesSet

这个方法会进入该类的initHandlerMethods

负责从applicationContext中扫描beans,然后从bean中查找并注册处理器方法

  1. //Scan beans in the ApplicationContext, detect and register handler methods.
  2. protected void initHandlerMethods() {
  3. ...
  4. //获取applicationContext中所有的bean name
  5. String[] beanNames = (this.detectHandlerMethodsInAncestorContexts ?
  6. BeanFactoryUtils.beanNamesForTypeIncludingAncestors(getApplicationContext(), Object.class) :
  7. getApplicationContext().getBeanNamesForType(Object.class));
  8. //遍历beanName数组
  9. for (String beanName : beanNames) {
  10. //isHandler会根据bean来判断bean定义中是否带有Controller注解或RequestMapping注解
  11. if (isHandler(getApplicationContext().getType(beanName))){
  12. detectHandlerMethods(beanName);
  13. }
  14. }
  15. handlerMethodsInitialized(getHandlerMethods());
  16. }
复制代码

RequestMappingHandlerMapping#isHandler

上图方法即判断当前bean定义是否带有Controlller注解或RequestMapping注解

如果只有RequestMapping生效吗?不会的!

因为这种情况下Spring初始化的时候不会把该类注册为Spring bean,遍历beanNames时不会遍历到这个类,所以这里把Controller换成Compoent也可以,不过一般不这么做

当确定bean为handler后,便会从该bean中查找出具体的handler方法(即Controller类下的具体定义的请求处理方法),查找代码如下

  1. /**
  2. * Look for handler methods in a handler
  3. * @param handler the bean name of a handler or a handler instance
  4. */
  5. protected void detectHandlerMethods(final Object handler) {
  6. //获取当前Controller bean的class对象
  7. Class<?> handlerType = (handler instanceof String) ?
  8. getApplicationContext().getType((String) handler) : handler.getClass();
  9. //避免重复调用 getMappingForMethod 来重建 RequestMappingInfo 实例
  10. final Map<Method, T> mappings = new IdentityHashMap<Method, T>();
  11. //同上,也是该Controller bean的class对象
  12. final Class<?> userType = ClassUtils.getUserClass(handlerType);
  13. //获取当前bean的所有handler method
  14. //根据 method 定义是否带有 RequestMapping
  15. //若有则创建RequestMappingInfo实例
  16. Set<Method> methods = HandlerMethodSelector.selectMethods(userType, new MethodFilter() {
  17. @Override
  18. public boolean matches(Method method) {
  19. T mapping = getMappingForMethod(method, userType);
  20. if (mapping != null) {
  21. mappings.put(method, mapping);
  22. return true;
  23. }
  24. else {
  25. return false;
  26. }
  27. }
  28. });
  29. //遍历并注册当前bean的所有handler method
  30. for (Method method : methods) {
  31. //注册handler method,进入以下方法
  32. registerHandlerMethod(handler, method, mappings.get(method));
  33. }
复制代码

以上代码有两个地方有调用了getMappingForMethod

使用方法和类型级别RequestMapping注解来创建RequestMappingInfo

  1. @Override
  2. protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) {
  3. RequestMappingInfo info = null;
  4. //获取method的@RequestMapping
  5. RequestMapping methodAnnotation = AnnotationUtils.findAnnotation(method, RequestMapping.class);
  6. if (methodAnnotation != null) {
  7. RequestCondition<?> methodCondition = getCustomMethodCondition(method);
  8. info = createRequestMappingInfo(methodAnnotation, methodCondition);
  9. //获取method所属bean的@RequtestMapping注解
  10. RequestMapping typeAnnotation = AnnotationUtils.findAnnotation(handlerType, RequestMapping.class);
  11. if (typeAnnotation != null) {
  12. RequestCondition<?> typeCondition = getCustomTypeCondition(handlerType);
  13. //合并两个@RequestMapping注解
  14. info = createRequestMappingInfo(typeAnnotation, typeCondition).combine(info);
  15. }
  16. }
  17. return info;
  18. }
复制代码

这个方法的作用就是根据handler method方法创建RequestMappingInfo对象。首先判断该mehtod是否含有RequestMpping注解。如果有则直接根据该注解的内容创建RequestMappingInfo对象。创建以后判断当前method所属的bean是否也含有RequestMapping注解。如果含有该注解则会根据该类上的注解创建一个RequestMappingInfo对象。然后在合并method上的RequestMappingInfo对象,最后返回合并后的对象。现在回过去看detectHandlerMethods方法,有两处调用了getMappingForMethod方法,个人觉得这里是可以优化的,在第一处判断method时否为handler时,创建的RequestMappingInfo对象可以保存起来,直接拿来后面使用,就少了一次创建RequestMappingInfo对象的过程。然后紧接着进入registerHandlerMehtod方法,如下

  1. protected void registerHandlerMethod(Object handler, Method method, T mapping) {
  2. //创建HandlerMethod
  3. HandlerMethod newHandlerMethod = createHandlerMethod(handler, method);
  4. HandlerMethod oldHandlerMethod = handlerMethods.get(mapping);
  5. //检查配置是否存在歧义性
  6. if (oldHandlerMethod != null && !oldHandlerMethod.equals(newHandlerMethod)) {
  7. throw new IllegalStateException("Ambiguous mapping found. Cannot map '" + newHandlerMethod.getBean()
  8. + "' bean method \n" + newHandlerMethod + "\nto " + mapping + ": There is already '"
  9. + oldHandlerMethod.getBean() + "' bean method\n" + oldHandlerMethod + " mapped.");
  10. }
  11. this.handlerMethods.put(mapping, newHandlerMethod);
  12. if (logger.isInfoEnabled()) {
  13. logger.info("Mapped \"" + mapping + "\" onto " + newHandlerMethod);
  14. }
  15. //获取@RequestMapping注解的value,然后添加value->RequestMappingInfo映射记录至urlMap中
  16. Set<String> patterns = getMappingPathPatterns(mapping);
  17. for (String pattern : patterns) {
  18. if (!getPathMatcher().isPattern(pattern)) {
  19. this.urlMap.add(pattern, mapping);
  20. }
  21. }
  22. }
复制代码

这里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...
异常

  1. @Controller
  2. @RequestMapping("/AmbiguousTest")
  3. public class AmbiguousTestController {
  4. @RequestMapping(value = "/test1")
  5. @ResponseBody
  6. public String test1(){
  7. return "method test1";
  8. }
  9. @RequestMapping(value = "/test1")
  10. @ResponseBody
  11. public String test2(){
  12. return "method test2";
  13. }
  14. }
复制代码

在SpingMVC启动(初始化)阶段检查RequestMapping配置是否有歧义,这是其中一处检查歧义的(后面还会提到一个在运行时检查歧义性的地方)。然后确认配置正常以后会把该RequestMappingInfo和HandlerMethod对象添加至handlerMethods(LinkedHashMap)中,静接着把RequestMapping注解的value和ReuqestMappingInfo对象添加至urlMap中。

registerHandlerMethod方法简单总结

该方法的主要有3个职责

1. 检查RequestMapping注解配置是否有歧义。

2. 构建RequestMappingInfo到HandlerMethod的映射map。该map便是AbstractHandlerMethodMapping的成员变量handlerMethods。LinkedHashMap。

3. 构建AbstractHandlerMethodMapping的成员变量urlMap,MultiValueMap。这个数据结构可以把它理解成Map>。其中String类型的key存放的是处理方法上RequestMapping注解的value。就是具体的uri

先有如下Controller

  1. @Controller
  2. @RequestMapping("/UrlMap")
  3. public class UrlMapController {
  4. @RequestMapping(value = "/test1", method = RequestMethod.GET)
  5. @ResponseBody
  6. public String test1(){
  7. return "method test1";
  8. }
  9. @RequestMapping(value = "/test1")
  10. @ResponseBody
  11. public String test2(){
  12. return "method test2";
  13. }
  14. @RequestMapping(value = "/test3")
  15. @ResponseBody
  16. public String test3(){
  17. return "method test3";
  18. }
  19. }
复制代码

初始化完成后,对应AbstractHandlerMethodMapping的urlMap的结构如下

以上便是SpringMVC初始化的主要过程

查找过程

为了理解查找流程,带着一个问题来看,现有如下Controller

  1. @Controller
  2. @RequestMapping("/LookupTest")
  3. public class LookupTestController {
  4. @RequestMapping(value = "/test1", method = RequestMethod.GET)
  5. @ResponseBody
  6. public String test1(){
  7. return "method test1";
  8. }
  9. @RequestMapping(value = "/test1", headers = "Referer=https://www.baidu.com")
  10. @ResponseBody
  11. public String test2(){
  12. return "method test2";
  13. }
  14. @RequestMapping(value = "/test1", params = "id=1")
  15. @ResponseBody
  16. public String test3(){
  17. return "method test3";
  18. }
  19. @RequestMapping(value = "/*")
  20. @ResponseBody
  21. public String test4(){
  22. return "method test4";
  23. }
  24. }
复制代码

有如下请求

这个请求会进入哪一个方法?

web容器(Tomcat、jetty)接收请求后,交给DispatcherServlet处理。FrameworkServlet调用对应请求方法(eg:get调用doGet),然后调用processRequest方法。进入processRequest方法后,一系列处理后,在line:936进入doService方法。然后在Line856进入doDispatch方法。在line:896获取当前请求的处理器handler。然后进入AbstractHandlerMethodMapping的lookupHandlerMethod方法。代码如下

  1. protected HandlerMethod lookupHandlerMethod(String lookupPath, HttpServletRequest request) throws Exception {
  2. List<Match> matches = new ArrayList<Match>();
  3. //根据uri获取直接匹配的RequestMappingInfos
  4. List<T> directPathMatches = this.urlMap.get(lookupPath);
  5. if (directPathMatches != null) {
  6. addMatchingMappings(directPathMatches, matches, request);
  7. }
  8. //不存在直接匹配的RequetMappingInfo,遍历所有RequestMappingInfo
  9. if (matches.isEmpty()) {
  10. // No choice but to go through all mappings
  11. addMatchingMappings(this.handlerMethods.keySet(), matches, request);
  12. }
  13. //获取最佳匹配的RequestMappingInfo对应的HandlerMethod
  14. if (!matches.isEmpty()) {
  15. Comparator<Match> comparator = new MatchComparator(getMappingComparator(request));
  16. Collections.sort(matches, comparator);
  17. if (logger.isTraceEnabled()) {
  18. logger.trace("Found " + matches.size() + " matching mapping(s) for [" + lookupPath + "] : " + matches);
  19. }
  20. //再一次检查配置的歧义性
  21. Match bestMatch = matches.get(0);
  22. if (matches.size() > 1) {
  23. Match secondBestMatch = matches.get(1);
  24. if (comparator.compare(bestMatch, secondBestMatch) == 0) {
  25. Method m1 = bestMatch.handlerMethod.getMethod();
  26. Method m2 = secondBestMatch.handlerMethod.getMethod();
  27. throw new IllegalStateException(
  28. "Ambiguous handler methods mapped for HTTP path '" + request.getRequestURL() + "': {" +
  29. m1 + ", " + m2 + "}");
  30. }
  31. }
  32. handleMatch(bestMatch.mapping, lookupPath, request);
  33. return bestMatch.handlerMethod;
  34. }
  35. else {
  36. return handleNoMatch(handlerMethods.keySet(), lookupPath, request);
  37. }
  38. }
复制代码

进入lookupHandlerMethod方法,其中lookupPath="/LookupTest/test1",根据lookupPath,也就是请求的uri。直接查找urlMap,获取直接匹配的RequestMappingInfo list。这里会匹配到3个RequestMappingInfo。如下

然后进入addMatchingMappings方法

  1. private void addMatchingMappings(Collection<T> mappings, List<Match> matches, HttpServletRequest request) {
  2. for (T mapping : mappings) {
  3. T match = getMatchingMapping(mapping, request);
  4. if (match != null) {
  5. matches.add(new Match(match, handlerMethods.get(mapping)));
  6. }
  7. }
  8. }
复制代码

这个方法的职责是遍历当前请求的uri和mappings中的RequestMappingInfo能否匹配上,如果能匹配上,创建一个相同的RequestMappingInfo对象。再获取RequestMappingInfo对应的handlerMethod。然后创建一个Match对象添加至matches list中。执行完addMatchingMappings方法,回到lookupHandlerMethod。这时候matches还有3个能匹配上的RequestMappingInfo对象。接下来的处理便是对matchers列表进行排序,然后获取列表的第一个元素作为最佳匹配。返回Match的HandlerMethod。这里进入RequestMappingInfo的compareTo方法,看一下具体的排序逻辑。代码如下

  1. public int compareTo(RequestMappingInfo other, HttpServletRequest request) {
  2. int result = patternsCondition.compareTo(other.getPatternsCondition(), request);
  3. if (result != 0) {
  4. return result;
  5. }
  6. result = paramsCondition.compareTo(other.getParamsCondition(), request);
  7. if (result != 0) {
  8. return result;
  9. }
  10. result = headersCondition.compareTo(other.getHeadersCondition(), request);
  11. if (result != 0) {
  12. return result;
  13. }
  14. result = consumesCondition.compareTo(other.getConsumesCondition(), request);
  15. if (result != 0) {
  16. return result;
  17. }
  18. result = producesCondition.compareTo(other.getProducesCondition(), request);
  19. if (result != 0) {
  20. return result;
  21. }
  22. result = methodsCondition.compareTo(other.getMethodsCondition(), request);
  23. if (result != 0) {
  24. return result;
  25. }
  26. result = customConditionHolder.compareTo(other.customConditionHolder, request);
  27. if (result != 0) {
  28. return result;
  29. }
  30. return 0;
  31. }
复制代码

代码里可以看出,匹配的先后顺序是value>params>headers>consumes>produces>methods>custom,看到这里,前面的问题就能轻易得出答案了。在value相同的情况,params更能先匹配。所以那个请求会进入test3()方法。再回到lookupHandlerMethod,在找到HandlerMethod。SpringMVC还会这里再一次检查配置的歧义性,这里检查的原理是通过比较匹配度最高的两个RequestMappingInfo进行比较。此处可能会有疑问在初始化SpringMVC有检查配置的歧义性,这里为什么还会检查一次。假如现在Controller中有如下两个方法,以下配置是能通过初始化歧义性检查的。

  1. @RequestMapping(value = "/test5", method = {RequestMethod.GET, RequestMethod.POST})
  2. @ResponseBody
  3. public String test5(){
  4. return "method test5";
  5. }
  6. @RequestMapping(value = "/test5", method = {RequestMethod.GET, RequestMethod.DELETE})
  7. @ResponseBody
  8. public String test6(){
  9. return "method test6";
  10. }
复制代码

现在执行 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数。代码如下

  1. public int compareTo(RequestMethodsRequestCondition other, HttpServletRequest request) {
  2. return other.methods.size() - this.methods.size();
  3. }
复制代码

什么时候匹配通配符?当通过urlMap获取不到直接匹配value的RequestMappingInfo时才会走通配符匹配进入addMatchingMappings方法。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对程序员之家的支持。



回复

使用道具 举报