美文网首页
springmvc源码概读

springmvc源码概读

作者: sunshine_5219 | 来源:发表于2019-08-11 16:55 被阅读0次

流程图:

SpringMVC-arch3.png

首先介绍初始化工作,在应用服务器启动的时候,会通过beanFactory 加载应用所需的bean,包括controller,一般beanname都是字符串 对应contoller类的类名(只是开头是小写的 如KingContrlloer对应的beanName 既为kingController,默认的加载bean工厂为 DefaultListableBeanFactory beanFactory;

会将controller里的方法以及访问url路径都会关联起来。通过bean获取class,通过class获取对应类里面的方法 这个比较好理解,但是如何将方法和请求url关联起来的呢?如下所示:

//应用服务器启动的时候 会把对应的 controller和controller的方法加载进去


    protected void detectHandlerMethods(Object handler) {

       Class<?> handlerType = (handler instanceof String ?

             obtainApplicationContext().getType((String) handler) : handler.getClass());

      if (handlerType != null) {

         Class<?> userType = ClassUtils.getUserClass(handlerType);

Map<Method, T> methods = MethodIntrospector.selectMethods(userType,

                 (MethodIntrospector.MetadataLookup<T>) method -> {

                     try {

                         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);

             registerHandlerMethod(handler, invocableMethod, mapping);

         });

     }

   }

}

selectMethods调用链如下:

//通过bean工厂生产出环境所需的各个bean,包括controller bean,通过bean 可找到其对应的class,通过反射即可获取得到对应bean里面的方法,然后就是方法如何和访问连接挂钩的


       //核心调用方法

       T result = metadataLookup.inspect(specificMethod);

  }

 //通过方法找到对应的 请求映射信息

  RequestMappingInfo info = createRequestMappingInfo(method);//获取得到映射路径

  //将方法和注解的url关联起来的方法 在详细的话 可以自我去研究

A annotation = element.getDeclaredAnnotation(annotationType);//获取得到requestMapping(url)路径 didi() 对应url路径

后面请求url访问控制层的 handlerMapping和handlerAdapter也会进行初始化

>>>>>initHandlerMappings(context);//ApplicationContext从springmvc-webmvc中的dispatchServlet.properties中获取如下映射

            >>>>org.springframework.web.servlet.HandlerMapping=org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping,\

                  org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping

         >>>>>initHandlerAdapters(context);

             >>>>>org.springframework.web.servlet.HandlerAdapter=org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter,\

                 org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter,\

                 org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter

准备工作做好了之后,才开始真正的接受请求的访问。

请求顺序如 流程图所示,这里只会截取核心的方法,大致操作流程如下:

     DispatchServelt>>doService()>>doDispatch(req,res)

                 ① >>getHandler(processedRequest)>>     

                 ②     >> HandlerExecutionChain mappedhandler = mapping.getHandler(request);//通过请求url在handerMapping(handler实现方式有多种,所     

                                 以才需要映射)找到对应的处理器和拦截器,封装成处理器执行链。

                 ③         >>>>HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());//由处理器执行链内的执行器去获取对应的执行器适配器,       

                                                                由处理器执行适配器去控制 拦截器和执行调用

                 ④             >>mv = ha.handle(processedRequest, response, mappedHandler.getHandler());//调用handler里对应的方法并获取返回的modelAndView

后续的找到对应的视图解析器,解析完成返回对应view响应回客户端。

针对第②步骤核心源码:如何通过url获取得到对应的处理器以及对应方法?

>>Object handler = getHandlerInternal(request); --public abstract class AbstractHandlerMethodMapping<T> extends

                                                                             AbstractHandlerMapping implements InitializingBean

                            protected HandlerMethod getHandlerInternal(HttpServletRequest request) throws Exception {

                                    String lookupPath = getUrlPathHelper().getLookupPathForRequest(request);//请求后缀的url

                                    this.mappingRegistry.acquireReadLock();

                                    try {

                                        HandlerMethod handlerMethod = lookupHandlerMethod(lookupPath, request);//关键步骤 通过对应映射              

                                                     方法找到对应的方法

                                        return (handlerMethod != null ? handlerMethod.createWithResolvedBean() : null);

                                    }

                                    finally {

                                        this.mappingRegistry.releaseReadLock();

                                    }

                            }

                //以上步骤 已经找到对应的handler和调用方法以及对应拦截器,通过一个调用执行链对象返回,同时下一步要获取 对应的HandlerAdapter
``

针对第④步核心源码:处理器适配器handlerAdapter如何执行handler内的方法?

                @Override

                protected ModelAndView handleInternal(HttpServletRequest request,

                        HttpServletResponse response, HandlerMethod handlerMethod) throws Exception {

                    ModelAndView mav;

                    checkRequest(request);

                    // Execute invokeHandlerMethod in synchronized block if required.

                    if (this.synchronizeOnSession) {

                        HttpSession session = request.getSession(false);

                        if (session != null) {

                            Object mutex = WebUtils.getSessionMutex(session);

                            synchronized (mutex) {

                                mav = invokeHandlerMethod(request, response, handlerMethod);

                            }

                        }

                        else {

                            // No HttpSession available -> no mutex necessary

                            mav = invokeHandlerMethod(request, response, handlerMethod);

                        }

                    }

                    else {

                        // No synchronization on session demanded at all...

                        mav = invokeHandlerMethod(request, response, handlerMethod);

                    }

                    if (!response.containsHeader(HEADER_CACHE_CONTROL)) {

                        if (getSessionAttributesHandler(handlerMethod).hasSessionAttributes()) {

                            applyCacheSeconds(response, this.cacheSecondsForSessionAttributeHandlers);

                        }

                        else {

                            prepareResponse(response);

                        }

                    }

                    return mav;

                }

                //最终方法调用执行通过

                    @CallerSensitive

                    public Object invoke(Object obj, Object... args)

                        throws IllegalAccessException, IllegalArgumentException,

                           InvocationTargetException

                    {

                        if (!override) {

                            if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {

                                Class<?> caller = Reflection.getCallerClass();

                                checkAccess(caller, clazz, obj, modifiers);

                            }

                        }

                        MethodAccessor ma = methodAccessor;             // read volatile

                        if (ma == null) {

                            ma = acquireMethodAccessor();

                        }

                        return ma.invoke(obj, args);

                    }

相关文章

网友评论

      本文标题:springmvc源码概读

      本文链接:https://www.haomeiwen.com/subject/jyssjctx.html