SpringMVC源码关于ModelAndView

首先这个对象返回的数据中主要包含模型数据和逻辑视图名,整个流程图如下所示:

SpringMVC源码关于ModelAndView_第1张图片
image.png

在之前讲到的doDispatch()方法中,获取到相关的HandlerExcutionChain和handlerAdapter对象,然后调用handlerAdapter的方法handler(),传入request,response,handler三个参数,之后调用handleInternal方法

    protected ModelAndView handleInternal(HttpServletRequest request, HttpServletResponse response, HandlerMethod handlerMethod)    throws Exception {
           this.checkRequest(request);
           ModelAndView mav;
           if (this.synchronizeOnSession) {
               HttpSession session = request.getSession(false);
               if (session != null) {
                   Object mutex = WebUtils.getSessionMutex(session);
                   synchronized(mutex) {
                       mav = this.invokeHandlerMethod(request, response, handlerMethod);
                   }
               } else {
                   mav = this.invokeHandlerMethod(request, response, handlerMethod);
               }
           } else {
               mav = this.invokeHandlerMethod(request, response, handlerMethod);
           }
    
           if (!response.containsHeader("Cache-Control")) {
               if (this.getSessionAttributesHandler(handlerMethod).hasSessionAttributes()) {
                   this.applyCacheSeconds(response, this.cacheSecondsForSessionAttributeHandlers);
               } else {
                   this.prepareResponse(response);
               }
           }
    
           return mav;
       }

这个方法会先检查一下request是否符合要求,然后再检测是否同步开启session,默认是false,然后这个方法中会调用invokeHandlerMethod()方法获取mav

    rotected ModelAndView invokeHandlerMethod(HttpServletRequest request, HttpServletResponse response, HandlerMethod handlerMethod)    hrows Exception {
           ServletWebRequest webRequest = new ServletWebRequest(request, response);

           Object result;
           try {
               WebDataBinderFactory binderFactory = this.getDataBinderFactory(handlerMethod);
               ModelFactory modelFactory = this.getModelFactory(handlerMethod, binderFactory);
               ServletInvocableHandlerMethod invocableMethod = this.createInvocableHandlerMethod(handlerMethod);
               invocableMethod.setHandlerMethodArgumentResolvers(this.argumentResolvers);
               invocableMethod.setHandlerMethodReturnValueHandlers(this.returnValueHandlers);
               invocableMethod.setDataBinderFactory(binderFactory);
               invocableMethod.setParameterNameDiscoverer(this.parameterNameDiscoverer);
               ModelAndViewContainer mavContainer = new ModelAndViewContainer();
               mavContainer.addAllAttributes(RequestContextUtils.getInputFlashMap(request));
               modelFactory.initModel(webRequest, mavContainer, invocableMethod);
               mavContainer.setIgnoreDefaultModelOnRedirect(this.ignoreDefaultModelOnRedirect);
               AsyncWebRequest asyncWebRequest = WebAsyncUtils.createAsyncWebRequest(request, response);
               asyncWebRequest.setTimeout(this.asyncRequestTimeout);
               WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
               asyncManager.setTaskExecutor(this.taskExecutor);
               asyncManager.setAsyncWebRequest(asyncWebRequest);
               asyncManager.registerCallableInterceptors(this.callableInterceptors);
               asyncManager.registerDeferredResultInterceptors(this.deferredResultInterceptors);
               if (asyncManager.hasConcurrentResult()) {
                   result = asyncManager.getConcurrentResult();
                   mavContainer = (ModelAndViewContainer)asyncManager.getConcurrentResultContext()[0];
                   asyncManager.clearConcurrentResult();
                   if (this.logger.isDebugEnabled()) {
                       this.logger.debug("Found concurrent result value [" + result + "]");
                   }

                   invocableMethod = invocableMethod.wrapConcurrentResult(result);
               }

               invocableMethod.invokeAndHandle(webRequest, mavContainer, new Object[0]);
               if (!asyncManager.isConcurrentHandlingStarted()) {
                   ModelAndView var15 = this.getModelAndView(mavContainer, modelFactory, webRequest);
                   return var15;
               }

               result = null;
           } finally {
               webRequest.requestCompleted();
           }

           return (ModelAndView)result;
       }

首先先创建web容器的request请求,然后进行一系列参数设置和相关的方法,到一个重要的方法,invokeAndHandler(webRequest,mavContainer,new Object[0]),该方法是用于获取view的

    public void invokeAndHandle(ServletWebRequest webRequest, ModelAndViewContainer mavContainer, Object... providedArgs) throws        Exception {
            Object returnValue = this.invokeForRequest(webRequest, mavContainer, providedArgs);
            this.setResponseStatus(webRequest);
            if (returnValue == null) {
                if (this.isRequestNotModified(webRequest) || this.getResponseStatus() != null || mavContainer.isRequestHandled()) {
                    mavContainer.setRequestHandled(true);
                    return;
                }
            } else if (StringUtils.hasText(this.getResponseStatusReason())) {
                mavContainer.setRequestHandled(true);
                return;
            }
    
            mavContainer.setRequestHandled(false);
    
            try {
                this.returnValueHandlers.handleReturnValue(returnValue, this.getReturnValueType(returnValue), mavContainer, webRequest);
            } catch (Exception var6) {
                if (this.logger.isTraceEnabled()) {
                    this.logger.trace(this.getReturnValueHandlingErrorMessage("Error handling return value", returnValue), var6);
                }
    
                throw var6;
            }
        }

invokeAndHandler方法中调用了invokeForRequest()方法获取执行请求方法的返回值

    public Object invokeForRequest(NativeWebRequest request, ModelAndViewContainer mavContainer, Object... providedArgs) throws Exception {
           Object[] args = this.getMethodArgumentValues(request, mavContainer, providedArgs);
           if (this.logger.isTraceEnabled()) {
               this.logger.trace("Invoking '" + ClassUtils.getQualifiedMethodName(this.getMethod(), this.getBeanType()) + "' with arguments " + Arrays.toString(args));
           }

           Object returnValue = this.doInvoke(args);
           if (this.logger.isTraceEnabled()) {
               this.logger.trace("Method [" + ClassUtils.getQualifiedMethodName(this.getMethod(), this.getBeanType()) + "] returned [" + returnValue + "]");
           }

           return returnValue;
       }

首先先获取request请求的参数,输出成object数组,然后向doInvoke()方法传入该数组作为参数

    protected Object doInvoke(Object... args) throws Exception {
           ReflectionUtils.makeAccessible(this.getBridgedMethod());

           try {
               return this.getBridgedMethod().invoke(this.getBean(), args);
           } catch (IllegalArgumentException var5) {
               this.assertTargetBean(this.getBridgedMethod(), this.getBean(), args);
               String text = var5.getMessage() != null ? var5.getMessage() : "Illegal argument";
               throw new IllegalStateException(this.getInvocationErrorMessage(text, args), var5);
           } catch (InvocationTargetException var6) {
               Throwable targetException = var6.getTargetException();
               if (targetException instanceof RuntimeException) {
                   throw (RuntimeException)targetException;
               } else if (targetException instanceof Error) {
                   throw (Error)targetException;
               } else if (targetException instanceof Exception) {
                   throw (Exception)targetException;
               } else {
                   String text = this.getInvocationErrorMessage("Failed to invoke handler method", args);
                   throw new IllegalStateException(text, targetException);
               }
           }
       }

doInvoke()方法中重要的是getBridgeMethod().invoke(getBean(),args)方法的调用
getBridgeMethod()是获取Controller的执行请求的方法,然后通过反射机制,获取执行请求的返回值

这边可以思考下,为什么使用getBridgeMethod(),而不直接使用getMethod(),两个方法的返回值也是一样的

获取到方法的返回值,即view="index"后,一路返回到上一层,到invokeHandlerMethod()方法,执行该方法中的下一个方法getModelAndView(mavContainer,modelFactory,webRequest)

    private ModelAndView getModelAndView(ModelAndViewContainer mavContainer, ModelFactory modelFactory, NativeWebRequest webRequest)        throws Exception {
            modelFactory.updateModel(webRequest, mavContainer);
            if (mavContainer.isRequestHandled()) {
                return null;
            } else {
                ModelMap model = mavContainer.getModel();
                ModelAndView mav = new ModelAndView(mavContainer.getViewName(), model, mavContainer.getStatus());
                if (!mavContainer.isViewReference()) {
                    mav.setView((View)mavContainer.getView());
                }
    
                if (model instanceof RedirectAttributes) {
                    Map flashAttributes = ((RedirectAttributes)model).getFlashAttributes();
                    HttpServletRequest request = (HttpServletRequest)webRequest.getNativeRequest(HttpServletRequest.class);
                    RequestContextUtils.getOutputFlashMap(request).putAll(flashAttributes);
                }
    
                return mav;
            }
        }       

在这段代码里边,我们能看见,每个modelAndView都是通过代码自己new出来的,传入了三个参数,viewName,model和status,这三个参数都是通过mavContainer来获取的
第一个参数,viewName
mavContainer.getViewName()方法返回viewName,如果view是String类型的实例,那么返回view,否则返回null

第二个参数,model
mavContainer.getModel(), 得到defaultModel或者是redirectModel,之前在invokeHandlerMethod创建modelFactory的时候就设置了两个参数的值

第三个参数status
mavContainer.getStatus(),该方法返回的值的类型是HttpStatus,也就是状态码

最后返回modelAndView对象

参考链接:
https://blog.csdn.net/qq924862077/article/details/53944721
https://blog.csdn.net/u010233323/article/details/52515773

你可能感兴趣的:(SpringMVC源码关于ModelAndView)