url 和 Controller 的对应关系

很多人对这一块比较茫然,比如在网页输入 /index/test.do就找到对了对应的Controller 类。url和Controller 关系怎么建立的。

AbstractHandlerMethodMapping实现了InitializingBean接口。说明这个类会在依赖注入的初始化开始执行,也就是Init-method那个解析地方处理这个扩展点。其源码分析:



在AbstractHandlerMethodMapping#isHandler中判断了类上使用Controller或RequestMapping其中至少一个注解就可以.


在initHandlerMethods调用detectHandlerMethods方法

protected void detectHandlerMethods(final Object handler) {
   //获取原始的Class<?> 也就是 public void com.jshx.estate.page.controller.PageCoreController类型这种
   Class<?> handlerType = (handler instanceof String ?
         obtainApplicationContext().getType((String) handler) : handler.getClass());

   if (handlerType != null) {
      final Class<?> userType = ClassUtils.getUserClass(handlerType);
      Map<Method, T> methods = MethodIntrospector.selectMethods(userType,
            (MethodIntrospector.MetadataLookup<T>) method -> {
               try {
                  //获取该controller类的所有url
                  return getMappingForMethod(method, userType);
               } catch (Throwable ex) {
                  throw new IllegalStateException("Invalid mapping on handler class [" +
                        userType.getName() + "]: " + method, ex);
               }
            });
      if (logger.isDebugEnabled()) {
         logger.debug(methods.size() + " request handler methods found on " + userType + ": " + methods);
      }
      //对过滤到的每个method进行注册registerHandlerMethod
      methods.forEach((method, mapping) -> {
         Method invocableMethod = AopUtils.selectInvocableMethod(method, userType);
         registerHandlerMethod(handler, invocableMethod, mapping);
      });
   }
}

detectHandlerMethods调用getMappingForMethod,这个方法由子类RequestMappingHandlerMapping里面进行实现

回到detectHandlerMethods方法中,开始调用registerHandlerMethod方法


这样就完成了映射关系。说白了就是将完整/app/core/getArticles.do 和对应的public..... PageCoreController.getArticles()放到map中。用户输入链接后,通过Dispatcherservlet.doDispatch()获取url匹配到对应的类方法,然后通过反射实例化来处理逻辑。


上一篇: IOC容器中常用扩展点

下一篇: DispatcherServlet接收请求

猜你喜欢

转载自blog.csdn.net/m0_37444820/article/details/80798543