URL如何進(jìn)入SpringMVC的Controller方法中

請(qǐng)求時(shí)如何找到具體的Controller的方法的

  1. doGet等是如何而來
    FrameworkServlet繼承于HttpServletBean请唱,HttpServletBean繼承于HttpServlet
  2. doGet、doPost过蹂、doPut十绑、doDelete等http請(qǐng)求均會(huì)調(diào)用processRequest
    FrameworkServlet部分相關(guān)源碼如下:
@Override
    protected final void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }
    
protected final void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    ...
    doService(request, response);
    ...
}
  1. processRequest調(diào)用DispatcherServlet的doService
  2. doService調(diào)用doDispatch
    • doDispatch調(diào)用applyPreHandle,執(zhí)行所有HandlerInterceptor攔截器的preHandle方法
    • doDispatch中代碼mv = ha.handle(processedRequest, response, mappedHandler.getHandler());調(diào)用Controller的方法酷勺,如何調(diào)用孽惰,后面指出
    • doDispatch調(diào)用applyPostHandle,執(zhí)行所有HandlerInterceptor攔截器的postHandle方法
    • doDispatch調(diào)用processDispatchResult
      • processDispatchResult調(diào)用triggerAfterCompletion
      • triggerAfterCompletion方法執(zhí)行所有HandlerInterceptor攔截器的afterCompletion方法
  • DispatcherServlet部分相關(guān)源碼如下
 protected void initStrategies(ApplicationContext context) {
       ...
        this.initHandlerMappings(context);
        this.initHandlerAdapters(context);
    ...
    }
protected void doService(HttpServletRequest request, HttpServletResponse response) throws Exception {
   ...
     try {
         this.doDispatch(request, response);
     }
     ...
 }

protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
        ...
        if (!mappedHandler.applyPreHandle(processedRequest, response)) {
             return;
         }
         mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
         if (asyncManager.isConcurrentHandlingStarted()) {
             return;
         }
         this.applyDefaultViewName(processedRequest, mv);
         mappedHandler.applyPostHandle(processedRequest, response, mv);
    ...
     this.processDispatchResult(processedRequest, response, mappedHandler, mv, (Exception)dispatchException);
     ...
}

boolean applyPreHandle(HttpServletRequest request, HttpServletResponse response) throws Exception {
    HandlerInterceptor[] interceptors = getInterceptors();
    if (!ObjectUtils.isEmpty(interceptors)) {
        for (int i = 0; i < interceptors.length; i++) {
            HandlerInterceptor interceptor = interceptors[i];
            if (!interceptor.preHandle(request, response, this.handler)) {
                triggerAfterCompletion(request, response, null);
                return false;
            }
            this.interceptorIndex = i;
        }
    }
    return true;
}
    
void applyPostHandle(HttpServletRequest request, HttpServletResponse response, @Nullable ModelAndView mv) throws Exception {
     HandlerInterceptor[] interceptors = this.getInterceptors();
      if (!ObjectUtils.isEmpty(interceptors)) {
          for(int i = interceptors.length - 1; i >= 0; --i) {
              HandlerInterceptor interceptor = interceptors[i];
              interceptor.postHandle(request, response, this.handler, mv);
          }
      }
    }
    
private void processDispatchResult(HttpServletRequest request, HttpServletResponse response, @Nullable HandlerExecutionChain mappedHandler, @Nullable ModelAndView mv, @Nullable Exception exception) throws Exception {
        ...
        if (!WebAsyncUtils.getAsyncManager(request).isConcurrentHandlingStarted()) {
            if (mappedHandler != null) {
                mappedHandler.triggerAfterCompletion(request, response, (Exception)null);
            }
        }
    }
    
void triggerAfterCompletion(HttpServletRequest request, HttpServletResponse response, @Nullable Exception ex) throws Exception {
         ...
         interceptor.afterCompletion(request, response, this.handler, ex);
         ...
    }

doDispatch中代碼mv = ha.handle(processedRequest, response, mappedHandler.getHandler());調(diào)用Controller的方法

  1. ha為HandlerAdapter接口
  2. 具體實(shí)現(xiàn)使用RequestMappingHandlerAdapter
  3. RequestMappingHandlerAdapter extends AbstractHandlerMethodAdapter
//AbstractHandlerMethodAdapter的方法    
   public final ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       return this.handleInternal(request, response, (HandlerMethod)handler);
   }
@Nullable
   protected abstract ModelAndView handleInternal(HttpServletRequest var1, HttpServletResponse var2, HandlerMethod var3) throws Exception;
  1. 之后調(diào)用handleInternal的抽象方法(實(shí)際調(diào)用RequestMappingHandlerAdapter的handleInternal)鸥印,內(nèi)部再次調(diào)用invokeHandlerMethod方法
  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);
      }
     ...
  }
  @Nullable
  protected ModelAndView invokeHandlerMethod(HttpServletRequest request, HttpServletResponse response, HandlerMethod handlerMethod) throws Exception {
      ...
          ServletInvocableHandlerMethod invocableMethod = this.createInvocableHandlerMethod(handlerMethod);
      ...
          invocableMethod.invokeAndHandle(webRequest, mavContainer, new Object[0]);
      ...
}
  1. 在此調(diào)用 invocableMethod.invokeAndHandle(webRequest, mavContainer, new Object[0]);(ServletInvocableHandlerMethod類)
public void invokeAndHandle(ServletWebRequest webRequest, ModelAndViewContainer mavContainer, Object... providedArgs) throws Exception {
    Object returnValue = this.invokeForRequest(webRequest, mavContainer, providedArgs);
    ...
 }
@Nullable
public Object invokeForRequest(NativeWebRequest request, @Nullable ModelAndViewContainer mavContainer, Object... providedArgs) throws Exception {
   Object[] args = this.getMethodArgumentValues(request, mavContainer, providedArgs);
   if (this.logger.isTraceEnabled()) {
       this.logger.trace("Arguments: " + Arrays.toString(args));
   }
   return this.doInvoke(args);
}
  1. 調(diào)用invokeForRequest勋功,再調(diào)用doInvoke
@Nullable
    protected Object doInvoke(Object... args) throws Exception {
        ReflectionUtils.makeAccessible(this.getBridgedMethod());
        try {
            return this.getBridgedMethod().invoke(this.getBean(), args);
       ...
  1. 使用return this.getBridgedMethod().invoke(this.getBean(), args);將controller對(duì)應(yīng)坦报,并傳遞參數(shù)(modelFactory.initModel(webRequest, mavContainer, invocableMethod); //參數(shù)通過此傳遞進(jìn)入invocableMethod)
    controller是從哪里找到的,是在handlerMethod中傳遞過來的狂鞋。最早在doDispatch中

HandlerInterceptor攔截器的說明

public interface HandlerInterceptor {
    //進(jìn)入controller前進(jìn)行判斷片择,如果此處放回false,則直接返回
    //用途:如token的驗(yàn)證
    default boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        return true;
    }
    //controller執(zhí)行方法返回后執(zhí)行此操作
    default void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
    }
    //執(zhí)行操作返回前進(jìn)入到此方法骚揍,可以對(duì)其進(jìn)行加工等
    default void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
    }
}

參考

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末字管,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子信不,更是在濱河造成了極大的恐慌嘲叔,老刑警劉巖,帶你破解...
    沈念sama閱讀 212,884評(píng)論 6 492
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件抽活,死亡現(xiàn)場(chǎng)離奇詭異硫戈,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)下硕,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,755評(píng)論 3 385
  • 文/潘曉璐 我一進(jìn)店門丁逝,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人梭姓,你說我怎么就攤上這事霜幼。” “怎么了誉尖?”我有些...
    開封第一講書人閱讀 158,369評(píng)論 0 348
  • 文/不壞的土叔 我叫張陵罪既,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我铡恕,道長(zhǎng)琢感,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 56,799評(píng)論 1 285
  • 正文 為了忘掉前任没咙,我火速辦了婚禮,結(jié)果婚禮上千劈,老公的妹妹穿的比我還像新娘祭刚。我一直安慰自己,他們只是感情好墙牌,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,910評(píng)論 6 386
  • 文/花漫 我一把揭開白布涡驮。 她就那樣靜靜地躺著,像睡著了一般喜滨。 火紅的嫁衣襯著肌膚如雪捉捅。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 50,096評(píng)論 1 291
  • 那天虽风,我揣著相機(jī)與錄音棒口,去河邊找鬼寄月。 笑死,一個(gè)胖子當(dāng)著我的面吹牛无牵,可吹牛的內(nèi)容都是我干的漾肮。 我是一名探鬼主播,決...
    沈念sama閱讀 39,159評(píng)論 3 411
  • 文/蒼蘭香墨 我猛地睜開眼茎毁,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼克懊!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起七蜘,我...
    開封第一講書人閱讀 37,917評(píng)論 0 268
  • 序言:老撾萬榮一對(duì)情侶失蹤谭溉,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后橡卤,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體扮念,經(jīng)...
    沈念sama閱讀 44,360評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,673評(píng)論 2 327
  • 正文 我和宋清朗相戀三年蒜魄,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了扔亥。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 38,814評(píng)論 1 341
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡谈为,死狀恐怖旅挤,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情伞鲫,我是刑警寧澤粘茄,帶...
    沈念sama閱讀 34,509評(píng)論 4 334
  • 正文 年R本政府宣布,位于F島的核電站秕脓,受9級(jí)特大地震影響柒瓣,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜吠架,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 40,156評(píng)論 3 317
  • 文/蒙蒙 一芙贫、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧傍药,春花似錦磺平、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,882評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至俱诸,卻和暖如春菠劝,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背睁搭。 一陣腳步聲響...
    開封第一講書人閱讀 32,123評(píng)論 1 267
  • 我被黑心中介騙來泰國打工赶诊, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留笼平,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 46,641評(píng)論 2 362
  • 正文 我出身青樓甫何,卻偏偏與公主長(zhǎng)得像出吹,于是被迫代替她去往敵國和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子辙喂,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,728評(píng)論 2 351

推薦閱讀更多精彩內(nèi)容