SpringMVC源碼關于ModelAndView

首先這個對象返回的數據中主要包含模型數據和邏輯視圖名检访,整個流程圖如下所示:

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

首先先創(chuàng)建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()方法獲取執(zhí)行請求方法的返回值

    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的執(zhí)行請求的方法抬驴,然后通過反射機制缆巧,獲取執(zhí)行請求的返回值

這邊可以思考下,為什么使用getBridgeMethod()陕悬,而不直接使用getMethod(),兩個方法的返回值也是一樣的

獲取到方法的返回值胧卤,即view="index"后拼岳,一路返回到上一層,到invokeHandlerMethod()方法,執(zhí)行該方法中的下一個方法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<String, ?> 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創(chuàng)建modelFactory的時候就設置了兩個參數的值

第三個參數status
mavContainer.getStatus(),該方法返回的值的類型是HttpStatus叽奥,也就是狀態(tài)碼

最后返回modelAndView對象

參考鏈接:
https://blog.csdn.net/qq924862077/article/details/53944721
https://blog.csdn.net/u010233323/article/details/52515773

?著作權歸作者所有,轉載或內容合作請聯系作者
  • 序言:七十年代末痛侍,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子赵哲,更是在濱河造成了極大的恐慌君丁,老刑警劉巖,帶你破解...
    沈念sama閱讀 221,635評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件橡庞,死亡現場離奇詭異,居然都是意外死亡丑勤,警方通過查閱死者的電腦和手機吧趣,發(fā)現死者居然都...
    沈念sama閱讀 94,543評論 3 399
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來岔霸,“玉大人俯渤,你說我怎么就攤上這事〕砘澹” “怎么了?”我有些...
    開封第一講書人閱讀 168,083評論 0 360
  • 文/不壞的土叔 我叫張陵略水,是天一觀的道長劝萤。 經常有香客問我,道長跨释,這世上最難降的妖魔是什么厌处? 我笑而不...
    開封第一講書人閱讀 59,640評論 1 296
  • 正文 為了忘掉前任,我火速辦了婚禮缆娃,結果婚禮上瑰排,老公的妹妹穿的比我還像新娘。我一直安慰自己椭住,他們只是感情好,可當我...
    茶點故事閱讀 68,640評論 6 397
  • 文/花漫 我一把揭開白布葫掉。 她就那樣靜靜地躺著乘碑,像睡著了一般金拒。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上绪抛,一...
    開封第一講書人閱讀 52,262評論 1 308
  • 那天,我揣著相機與錄音笤休,去河邊找鬼症副。 笑死,一個胖子當著我的面吹牛闹啦,可吹牛的內容都是我干的辕坝。 我是一名探鬼主播,決...
    沈念sama閱讀 40,833評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼琳袄,長吁一口氣:“原來是場噩夢啊……” “哼纺酸!你這毒婦竟也來了?” 一聲冷哼從身側響起餐蔬,我...
    開封第一講書人閱讀 39,736評論 0 276
  • 序言:老撾萬榮一對情侶失蹤用含,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后啄骇,有當地人在樹林里發(fā)現了一具尸體,經...
    沈念sama閱讀 46,280評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡痪寻,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 38,369評論 3 340
  • 正文 我和宋清朗相戀三年橡类,在試婚紗的時候發(fā)現自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片顾画。...
    茶點故事閱讀 40,503評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖谱邪,靈堂內的尸體忽然破棺而出庶诡,到底是詐尸還是另有隱情,我是刑警寧澤末誓,帶...
    沈念sama閱讀 36,185評論 5 350
  • 正文 年R本政府宣布喇澡,位于F島的核電站,受9級特大地震影響撩幽,放射性物質發(fā)生泄漏。R本人自食惡果不足惜宪萄,卻給世界環(huán)境...
    茶點故事閱讀 41,870評論 3 333
  • 文/蒙蒙 一榨惰、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧居凶,春花似錦藤抡、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,340評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽替饿。三九已至,卻和暖如春视卢,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背惋砂。 一陣腳步聲響...
    開封第一講書人閱讀 33,460評論 1 272
  • 我被黑心中介騙來泰國打工蝶俱, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留饥漫,地道東北人。 一個月前我還...
    沈念sama閱讀 48,909評論 3 376
  • 正文 我出身青樓积蜻,卻偏偏與公主長得像彻消,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子丙笋,可洞房花燭夜當晚...
    茶點故事閱讀 45,512評論 2 359

推薦閱讀更多精彩內容