本文通過前端控制器源碼分析springmvc執行過程
1.前端控制器接收請求
調用doDispatch
方法
protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
HttpServletRequest processedRequest = request;
HandlerExecutionChain mappedHandler = null;
boolean multipartRequestParsed = false;
。。。。。
}
2.前端控制器調用HandlerMapping
(處理器映射器)根據url查找Handler
// Determine handler for the current request.
mappedHandler = getHandler(processedRequest);
/**
* Return the HandlerExecutionChain for this request.
*
Tries all handler mappings in order. * @param request current HTTP request * @return the HandlerExecutionChain, or [email protected] null} if no handler could be found */ protected HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception { for (HandlerMapping hm : this.handlerMappings) { if (logger.isTraceEnabled()) { logger.trace( "Testing handler map [" + hm + "] in DispatcherServlet with name '" + getServletName() + "'"); } HandlerExecutionChain handler = hm.getHandler(request); if (handler != null) { return handler; } } return null; }
3.調用處理器適配器執行Handler,得到執行的結果ModelAndView mv
在doDispatch
方法中
// Actually invoke the handler.
mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
4.視圖渲染,將model數據填充到request域
doDispatch
->processDispatchResult
->render
在render
方法中,視圖解析得到view
// We need to resolve the view name.
view = resolveViewName(mv.getViewName(), mv.getModelInternal(), locale, request);
調用view的渲染方法,將model數據填充到request域
在render
方法中,調用View
接口的render
方法
view.render(mv.getModelInternal(), request, response);
程序我也沒細讀,感覺分析比較淺,很多還沒弄懂,等我系統閱讀源碼後會整理一篇好點的。