javascript
SpringMVC工作原理之一:DispatcherServlet
一、DispatcherServlet 處理流程
在整個 Spring MVC 框架中,DispatcherServlet 處于核心位置,它負責協調和組織不同組件完成請求處理并返回響應工作。在看 DispatcherServlet 類之前,我們先來看一下請求處理的大致流程:
?
二、DispatcherServlet 源碼分析
DispatcherServlet 繼承自 HttpServlet,它遵循 Servlet 里的“init-service-destroy”三個階段,首先我們先來看一下它的 init() 階段。
1 初始化
1.1?HttpServletBean 的 init() 方法
DispatcherServlet 的 init() 方法在其父類?HttpServletBean?中實現的,它覆蓋了 GenericServlet 的 init() 方法,主要作用是加載 web.xml 中 DispatcherServlet 的?<init-param> 配置,并調用子類的初始化。下面是 init() 方法的具體代碼:
@Override public final void init() throws ServletException {try {// ServletConfigPropertyValues 是靜態內部類,使用 ServletConfig 獲取 web.xml 中配置的參數PropertyValues pvs = new ServletConfigPropertyValues(getServletConfig(), this.requiredProperties);// 使用 BeanWrapper 來構造 DispatcherServletBeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this);ResourceLoader resourceLoader = new ServletContextResourceLoader(getServletContext());bw.registerCustomEditor(Resource.class, new ResourceEditor(resourceLoader, getEnvironment()));initBeanWrapper(bw);bw.setPropertyValues(pvs, true);} catch (BeansException ex) {}// 讓子類實現的方法,這種在父類定義在子類實現的方式叫做模版方法模式initServletBean(); }?
1.2?FrameworkServlet 的 initServletBean() 方法
在 HttpServletBean 的?init() 方法中調用了?initServletBean() 這個方法,它是在?FrameworkServlet?類中實現的,主要作用是建立 WebApplicationContext 容器(有時也稱上下文),并加載 SpringMVC 配置文件中定義的 Bean 到改容器中,最后將該容器添加到 ServletContext 中。下面是?initServletBean() 方法的具體代碼:
@Override protected final void initServletBean() throws ServletException {try {// 初始化 WebApplicationContext (即SpringMVC的IOC容器)this.webApplicationContext = initWebApplicationContext();initFrameworkServlet();} catch (ServletException ex) {} catch (RuntimeException ex) {} }WebApplicationContext 繼承于 ApplicationContext 接口,從容器中可以獲取當前應用程序環境信息,它也是 SpringMVC 的 IOC 容器。下面是 initWebApplicationContext() 方法的具體代碼:
protected WebApplicationContext initWebApplicationContext() {// 獲取 ContextLoaderListener 初始化并注冊在 ServletContext 中的根容器,即 Spring 的容器WebApplicationContext rootContext =WebApplicationContextUtils.getWebApplicationContext(getServletContext());WebApplicationContext wac = null;if (this.webApplicationContext != null) {// 因為 WebApplicationContext 不為空,說明該類在構造時已經將其注入wac = this.webApplicationContext;if (wac instanceof ConfigurableWebApplicationContext) {ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) wac;if (!cwac.isActive()) {if (cwac.getParent() == null) {// 將 Spring 的容器設為 SpringMVC 容器的父容器cwac.setParent(rootContext);}configureAndRefreshWebApplicationContext(cwac);}}}if (wac == null) {// 如果 WebApplicationContext 為空,則進行查找,能找到說明上下文已經在別處初始化。wac = findWebApplicationContext();}if (wac == null) {// 如果 WebApplicationContext 仍為空,則以 Spring 的容器為父上下文建立一個新的。wac = createWebApplicationContext(rootContext);}if (!this.refreshEventReceived) {// 模版方法,由 DispatcherServlet 實現onRefresh(wac);}if (this.publishContext) {// 發布這個 WebApplicationContext 容器到 ServletContext 中String attrName = getServletContextAttributeName();getServletContext().setAttribute(attrName, wac);}return wac; }下面是查找?WebApplicationContext 的?findWebApplicationContext() 方法代碼:
protected WebApplicationContext findWebApplicationContext() {String attrName = getContextAttribute();if (attrName == null) {return null;}// 從 ServletContext 中查找已經發布的 WebApplicationContext 容器WebApplicationContext wac =WebApplicationContextUtils.getWebApplicationContext(getServletContext(), attrName);if (wac == null) {throw new IllegalStateException("No WebApplicationContext found: initializer not registered?");}return wac; }?
1.3 DispatcherServlet 的 onRefresh() 方法
建立好?WebApplicationContext(上下文)?后,通過 onRefresh(ApplicationContext context) 方法回調,進入 DispatcherServlet 類中。onRefresh() 方法,提供 SpringMVC 的初始化,具體代碼如下:
@Overrideprotected void onRefresh(ApplicationContext context) {initStrategies(context);}protected void initStrategies(ApplicationContext context) {initMultipartResolver(context);initLocaleResolver(context);initThemeResolver(context);initHandlerMappings(context);initHandlerAdapters(context);initHandlerExceptionResolvers(context);initRequestToViewNameTranslator(context);initViewResolvers(context);initFlashMapManager(context);}在 initStrategies() 方法中進行了各個組件的初始化,先來看一下這些組件的初始化方法,稍后再來詳細分析這些組件。
1.3.1?initHandlerMappings 方法
initHandlerMappings() 方法從?SpringMVC 的容器及 Spring 的容器中查找所有的 HandlerMapping 實例,并把它們放入到?handlerMappings 這個 list 中。這個方法并不是對?HandlerMapping 實例的創建,HandlerMapping 實例是在上面 WebApplicationContext 容器初始化,即 SpringMVC 容器初始化的時候創建的。
private void initHandlerMappings(ApplicationContext context) {this.handlerMappings = null;if (this.detectAllHandlerMappings) {// 從 SpringMVC 的 IOC 容器及 Spring 的 IOC 容器中查找 HandlerMapping 實例Map<String, HandlerMapping> matchingBeans =BeanFactoryUtils.beansOfTypeIncludingAncestors(context, HandlerMapping.class, true, false);if (!matchingBeans.isEmpty()) {this.handlerMappings = new ArrayList<HandlerMapping>(matchingBeans.values());// 按一定順序放置 HandlerMapping 對象OrderComparator.sort(this.handlerMappings);}} else {try {HandlerMapping hm = context.getBean(HANDLER_MAPPING_BEAN_NAME, HandlerMapping.class);this.handlerMappings = Collections.singletonList(hm);} catch (NoSuchBeanDefinitionException ex) {// Ignore, we'll add a default HandlerMapping later.}}// 如果沒有 HandlerMapping,則加載默認的if (this.handlerMappings == null) {this.handlerMappings = getDefaultStrategies(context, HandlerMapping.class);} }1.3.2?initHandlerAdapters 方法
private void initHandlerAdapters(ApplicationContext context) {this.handlerAdapters = null;if (this.detectAllHandlerAdapters) {// Find all HandlerAdapters in the ApplicationContext, including ancestor contexts.Map<String, HandlerAdapter> matchingBeans =BeanFactoryUtils.beansOfTypeIncludingAncestors(context, HandlerAdapter.class, true, false);if (!matchingBeans.isEmpty()) {this.handlerAdapters = new ArrayList<HandlerAdapter>(matchingBeans.values());// We keep HandlerAdapters in sorted order.OrderComparator.sort(this.handlerAdapters);}} else {try {HandlerAdapter ha = context.getBean(HANDLER_ADAPTER_BEAN_NAME, HandlerAdapter.class);this.handlerAdapters = Collections.singletonList(ha);} catch (NoSuchBeanDefinitionException ex) {// Ignore, we'll add a default HandlerAdapter later.}}// Ensure we have at least some HandlerAdapters, by registering// default HandlerAdapters if no other adapters are found.if (this.handlerAdapters == null) {this.handlerAdapters = getDefaultStrategies(context, HandlerAdapter.class);} }??
2 處理請求
HttpServlet 提供了 doGet()、doPost() 等方法,DispatcherServlet 中這些方法是在其父類 FrameworkServlet 中實現的,代碼如下:
@Override protected final void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {processRequest(request, response); } @Override protected final void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {processRequest(request, response); }這些方法又都調用了 processRequest() 方法,我們來看一下代碼:
protected final void processRequest(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {long startTime = System.currentTimeMillis();Throwable failureCause = null;// 返回與當前線程相關聯的 LocaleContextLocaleContext previousLocaleContext = LocaleContextHolder.getLocaleContext();// 根據請求構建 LocaleContext,公開請求的語言環境為當前語言環境LocaleContext localeContext = buildLocaleContext(request);// 返回當前綁定到線程的 RequestAttributesRequestAttributes previousAttributes = RequestContextHolder.getRequestAttributes();// 根據請求構建ServletRequestAttributesServletRequestAttributes requestAttributes = buildRequestAttributes(request, response, previousAttributes);// 獲取當前請求的 WebAsyncManager,如果沒有找到則創建WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request); asyncManager.registerCallableInterceptor(FrameworkServlet.class.getName(), new RequestBindingInterceptor());// 使 LocaleContext 和 requestAttributes 關聯initContextHolders(request, localeContext, requestAttributes);try {// 由 DispatcherServlet 實現doService(request, response);} catch (ServletException ex) {} catch (IOException ex) {} catch (Throwable ex) {} finally {// 重置 LocaleContext 和 requestAttributes,解除關聯resetContextHolders(request, previousLocaleContext, previousAttributes);if (requestAttributes != null) {requestAttributes.requestCompleted();}// 發布 ServletRequestHandlerEvent 事件publishRequestHandledEvent(request, startTime, failureCause);} }DispatcherServlet 的 doService() 方法主要是設置一些 request 屬性,并調用 doDispatch() 方法進行請求分發處理,doDispatch() 方法的主要過程是通過 HandlerMapping 獲取 Handler,再找到用于執行它的 HandlerAdapter,執行 Handler 后得到 ModelAndView ,ModelAndView 是連接“業務邏輯層”與“視圖展示層”的橋梁,接下來就要通過 ModelAndView 獲得 View,再通過它的 Model 對 View 進行渲染。doDispatch() 方法如下:
protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {HttpServletRequest processedRequest = request;HandlerExecutionChain mappedHandler = null;boolean multipartRequestParsed = false;// 獲取當前請求的WebAsyncManager,如果沒找到則創建并與請求關聯WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);try {ModelAndView mv = null;Exception dispatchException = null;try {// 檢查是否有 Multipart,有則將請求轉換為 Multipart 請求processedRequest = checkMultipart(request);multipartRequestParsed = (processedRequest != request);// 遍歷所有的 HandlerMapping 找到與請求對應的 Handler,并將其與一堆攔截器封裝到 HandlerExecution 對象中。mappedHandler = getHandler(processedRequest);if (mappedHandler == null || mappedHandler.getHandler() == null) {noHandlerFound(processedRequest, response);return;}// 遍歷所有的 HandlerAdapter,找到可以處理該 Handler 的 HandlerAdapterHandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());// 處理 last-modified 請求頭 String method = request.getMethod();boolean isGet = "GET".equals(method);if (isGet || "HEAD".equals(method)) {long lastModified = ha.getLastModified(request, mappedHandler.getHandler());if (new ServletWebRequest(request, response).checkNotModified(lastModified) && isGet) {return;}}// 遍歷攔截器,執行它們的 preHandle() 方法if (!mappedHandler.applyPreHandle(processedRequest, response)) {return;}try {// 執行實際的處理程序mv = ha.handle(processedRequest, response, mappedHandler.getHandler());} finally {if (asyncManager.isConcurrentHandlingStarted()) {return;}}applyDefaultViewName(request, mv);// 遍歷攔截器,執行它們的 postHandle() 方法mappedHandler.applyPostHandle(processedRequest, response, mv);} catch (Exception ex) {dispatchException = ex;}// 處理執行結果,是一個 ModelAndView 或 Exception,然后進行渲染processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);} catch (Exception ex) {} catch (Error err) {} finally {if (asyncManager.isConcurrentHandlingStarted()) {// 遍歷攔截器,執行它們的 afterCompletion() 方法 mappedHandler.applyAfterConcurrentHandlingStarted(processedRequest, response);return;}// Clean up any resources used by a multipart request.if (multipartRequestParsed) {cleanupMultipart(processedRequest);}} }?
from:?https://www.cnblogs.com/tengyunhao/p/7518481.html
總結
以上是生活随笔為你收集整理的SpringMVC工作原理之一:DispatcherServlet的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Spring系列之beanFactory
- 下一篇: Spring 的IOC容器系列的设计与实