javascript
SpringMVC 执行流程解析
SpringMVC 執行流程解析
注:SpringMVC 版本 5.2.15
上面這張圖許多人都看過,本文試圖從源碼的角度帶大家分析一下該過程。
1. ContextLoaderListener
首先我們從 ContextLoaderListener 講起,它繼承自 ServletContextListener,用于監聽 Web 應用程序的啟動與停止。ContextLoaderListener 中的 contextInitialized() 方法用于初始化 Web 應用程序上下文。
ContextLoaderListener # contextInitialized
public class ContextLoaderListener extends ContextLoader implements ServletContextListener {.../*** Initialize the root web application context.*/@Overridepublic void contextInitialized(ServletContextEvent event) {initWebApplicationContext(event.getServletContext());}... }其中又調用了 initWebApplicationContext() 方法初始化 Web 應用程序上下文
ContextLoader # initWebApplicationContext
public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {if (servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) != null) {throw new IllegalStateException("Cannot initialize context because there is already a root application context present - " +"check whether you have multiple ContextLoader* definitions in your web.xml!");}servletContext.log("Initializing Spring root WebApplicationContext");Log logger = LogFactory.getLog(ContextLoader.class);if (logger.isInfoEnabled()) {logger.info("Root WebApplicationContext: initialization started");}long startTime = System.currentTimeMillis();try {if (this.context == null) {// 創建并保存應用程序上下文到屬性中this.context = createWebApplicationContext(servletContext);}if (this.context instanceof ConfigurableWebApplicationContext) {ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context;if (!cwac.isActive()) {if (cwac.getParent() == null) {ApplicationContext parent = loadParentContext(servletContext);cwac.setParent(parent);}// 配置并刷新當前 Web 應用程序上下文configureAndRefreshWebApplicationContext(cwac, servletContext);}}servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);ClassLoader ccl = Thread.currentThread().getContextClassLoader();if (ccl == ContextLoader.class.getClassLoader()) {currentContext = this.context;}else if (ccl != null) {currentContextPerThread.put(ccl, this.context);}if (logger.isInfoEnabled()) {long elapsedTime = System.currentTimeMillis() - startTime;logger.info("Root WebApplicationContext initialized in " + elapsedTime + " ms");}return this.context;}catch (RuntimeException | Error ex) {logger.error("Context initialization failed", ex);servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);throw ex;} }該方法中調用了 createWebApplicationContext() 方法創建了 Web 應用程序上下文,并調用 configureAndRefreshWebApplicationContext() 方法配置并刷新當前 Web 應用程序上下文。
ContextLoader # configureAndRefreshWebApplicationContext
protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac, ServletContext sc) {// 為當前 Web 應用程序上下文設置一個 idif (ObjectUtils.identityToString(wac).equals(wac.getId())) {String idParam = sc.getInitParameter(CONTEXT_ID_PARAM);if (idParam != null) {wac.setId(idParam);}else {wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +ObjectUtils.getDisplayString(sc.getContextPath()));}}// 設置 ServletContextwac.setServletContext(sc);String configLocationParam = sc.getInitParameter(CONFIG_LOCATION_PARAM);if (configLocationParam != null) {wac.setConfigLocation(configLocationParam);}ConfigurableEnvironment env = wac.getEnvironment();if (env instanceof ConfigurableWebEnvironment) {((ConfigurableWebEnvironment) env).initPropertySources(sc, null);}customizeContext(sc, wac);// 刷新當前應用程序上下文wac.refresh(); }該方法的主要作用是刷新當前應用程序上下文,實際上就是調用了 AbstractApplicationContext # refresh 方法,也就是我們常講的啟動 IOC 容器,這個方法里的具體內容這里就不講了。
總結:
ContextLoaderListener 的作用是準備好 Web 應用程序上下文,啟動 IOC 容器。
2. DispatcherServlet 初始化邏輯
先看一張 DispatcherServlet 的繼承關系圖
其中 HttpServletBean 有一個 init() 方法,該方法是一個初始化方法
HttpServletBean # init
@Override public final void init() throws ServletException {// 獲取 web.xml 文件中的 <init-param> 中的參數保存到 PropertyValues 中PropertyValues pvs = new ServletConfigPropertyValues(getServletConfig(), this.requiredProperties);if (!pvs.isEmpty()) {try {// 將 HttpServletBean 對象轉換為 BeanWrapper 對象BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this);// 創建一個 ResourceLoader 對象ResourceLoader resourceLoader = new ServletContextResourceLoader(getServletContext());// 注冊屬性編輯器bw.registerCustomEditor(Resource.class, new ResourceEditor(resourceLoader, getEnvironment()));// 初始化 BeanWrapper 對象initBeanWrapper(bw);// 將屬性值保存到 BeanWrapper 中bw.setPropertyValues(pvs, true);}catch (BeansException ex) {if (logger.isErrorEnabled()) {logger.error("Failed to set bean properties on servlet '" + getServletName() + "'", ex);}throw ex;}}// Let subclasses do whatever initialization they like.initServletBean(); }該方法中首先嘗試獲取 web.xml 文件中的 init-param 值,如果獲取到的話,則將它保存到 BeanWrapper 中。最后調用了 initServletBean() 方法
FrameworkServlet # initServletBean
@Override protected final void initServletBean() throws ServletException {getServletContext().log("Initializing Spring " + getClass().getSimpleName() + " '" + getServletName() + "'");if (logger.isInfoEnabled()) {logger.info("Initializing Servlet '" + getServletName() + "'");}long startTime = System.currentTimeMillis();try {// 初始化 WebApplicationContextthis.webApplicationContext = initWebApplicationContext();// 空方法,可由子類去具體實現initFrameworkServlet();}catch (ServletException | RuntimeException ex) {logger.error("Context initialization failed", ex);throw ex;}if (logger.isDebugEnabled()) {String value = this.enableLoggingRequestDetails ?"shown which may lead to unsafe logging of potentially sensitive data" :"masked to prevent unsafe logging of potentially sensitive data";logger.debug("enableLoggingRequestDetails='" + this.enableLoggingRequestDetails +"': request parameters and headers will be " + value);}if (logger.isInfoEnabled()) {logger.info("Completed initialization in " + (System.currentTimeMillis() - startTime) + " ms");} }該方法中主要調用了 initWebApplicationContext() 去初始化 web 應用程序上下文
FrameworkServlet # initWebApplicationContext
protected WebApplicationContext initWebApplicationContext() {WebApplicationContext rootContext =WebApplicationContextUtils.getWebApplicationContext(getServletContext());WebApplicationContext wac = null;if (this.webApplicationContext != null) {wac = this.webApplicationContext;if (wac instanceof ConfigurableWebApplicationContext) {ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) wac;if (!cwac.isActive()) {if (cwac.getParent() == null) {cwac.setParent(rootContext);}// 配置并刷新 web 應用程序上下文configureAndRefreshWebApplicationContext(cwac);}}}if (wac == null) {// 去獲取 web 應用程序上下文wac = findWebApplicationContext();}if (wac == null) {// 創建 web 應用程序上下文wac = createWebApplicationContext(rootContext);}if (!this.refreshEventReceived) {synchronized (this.onRefreshMonitor) {// 刷新 web 應用程序上下文onRefresh(wac);}}if (this.publishContext) {String attrName = getServletContextAttributeName();getServletContext().setAttribute(attrName, wac);}return wac; }該方法主要是去創建一個新的 web 應用程序上下文,然后調用 onRefresh() 方法
FrameworkServlet # onRefresh
@Override protected void onRefresh(ApplicationContext context) {initStrategies(context); }DispatcherServlet # initStrategies
protected void initStrategies(ApplicationContext context) {// 初始化 文件上傳解析器initMultipartResolver(context);// 初始化 本地化解析器initLocaleResolver(context);// 初始化 主題解析器initThemeResolver(context);// 初始化 處理器映射器initHandlerMappings(context);// 初始化 處理器映射適配器initHandlerAdapters(context);// 初始化 異常解析器initHandlerExceptionResolvers(context);// 初始化 請求獲取視圖名轉換器initRequestToViewNameTranslator(context);// 初始化 視圖解析器initViewResolvers(context);// 初始化 FlashMap 管理器initFlashMapManager(context); }該方法中初始化了 SpringMVC 的九大組件。我以 initHandlerMappings() 方法為例講解一下,其他組件的獲取方式和它基本相同。
DispatcherServlet # initHandlerMappings
/*** Initialize the HandlerMappings used by this class.* <p>If no HandlerMapping beans are defined in the BeanFactory for this namespace,* we default to BeanNameUrlHandlerMapping.*/ private void initHandlerMappings(ApplicationContext context) {this.handlerMappings = null;// 從 ApplicationContext 中去獲取 HandlerMapping// 獲取不到的話去獲取對象名為 handlerMapping 的 HandlerMapping 對象// 再獲取不到的話則注冊默認的 HandlerMappingif (this.detectAllHandlerMappings) {// 從 ApplicationContext 中獲取Map<String, HandlerMapping> matchingBeans =BeanFactoryUtils.beansOfTypeIncludingAncestors(context, HandlerMapping.class, true, false);if (!matchingBeans.isEmpty()) {this.handlerMappings = new ArrayList<>(matchingBeans.values());AnnotationAwareOrderComparator.sort(this.handlerMappings);}}else {try {// 獲取名為 handlerMapping 的 HandlerMapping 對象HandlerMapping hm = context.getBean(HANDLER_MAPPING_BEAN_NAME, HandlerMapping.class);this.handlerMappings = Collections.singletonList(hm);}catch (NoSuchBeanDefinitionException ex) {}}if (this.handlerMappings == null) {// 注冊默認的 HandlerMappingthis.handlerMappings = getDefaultStrategies(context, HandlerMapping.class);if (logger.isTraceEnabled()) {logger.trace("No HandlerMappings declared for servlet '" + getServletName() +"': using default strategies from DispatcherServlet.properties");}} }該方法首先從 ApplicationContext 中去獲取 HandlerMapping,獲取不到的話去獲取對象名為 handlerMapping 的 HandlerMapping 對象,再獲取不到的話則注冊默認的 HandlerMapping。我們看一下這個默認的 HandlerMapping 是怎么獲取的。
DispatcherServlet # getDefaultStrategies
protected <T> List<T> getDefaultStrategies(ApplicationContext context, Class<T> strategyInterface) {String key = strategyInterface.getName();// 獲取邏輯在這String value = defaultStrategies.getProperty(key);if (value != null) {// 獲取類名String[] classNames = StringUtils.commaDelimitedListToStringArray(value);List<T> strategies = new ArrayList<>(classNames.length);for (String className : classNames) {try {// 創建 Class 對象Class<?> clazz = ClassUtils.forName(className, DispatcherServlet.class.getClassLoader());Object strategy = createDefaultStrategy(context, clazz);strategies.add((T) strategy);}catch (ClassNotFoundException ex) {throw new BeanInitializationException("Could not find DispatcherServlet's default strategy class [" + className +"] for interface [" + key + "]", ex);}catch (LinkageError err) {throw new BeanInitializationException("Unresolvable class definition for DispatcherServlet's default strategy class [" +className + "] for interface [" + key + "]", err);}}return strategies;}else {return new LinkedList<>();} }可以看到會嘗試從 defaultStrategies 中獲取值。然后將獲取到的值通過 Class.forName() 方法去創建對象。那么我們看一下這個 defaultStrategies 是什么。
private static final Properties defaultStrategies;static {try {ClassPathResource resource = new ClassPathResource(DEFAULT_STRATEGIES_PATH, DispatcherServlet.class);defaultStrategies = PropertiesLoaderUtils.loadProperties(resource);}catch (IOException ex) {throw new IllegalStateException("Could not load '" + DEFAULT_STRATEGIES_PATH + "': " + ex.getMessage());} } private static final String DEFAULT_STRATEGIES_PATH = "DispatcherServlet.properties";defaultStrategies 是 DispatcherServlet 中的一個屬性,類型為 Properties 。在 DispatcherServlet 的靜態代碼塊中加載了 DispatcherServlet.properties 文件到了 defaultStrategies 中。
DispatcherServlet.properties
org.springframework.web.servlet.LocaleResolver=org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolverorg.springframework.web.servlet.ThemeResolver=org.springframework.web.servlet.theme.FixedThemeResolverorg.springframework.web.servlet.HandlerMapping=org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping,\org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping,\org.springframework.web.servlet.function.support.RouterFunctionMappingorg.springframework.web.servlet.HandlerAdapter=org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter,\org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter,\org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter,\org.springframework.web.servlet.function.support.HandlerFunctionAdapterorg.springframework.web.servlet.HandlerExceptionResolver=org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver,\org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver,\org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolverorg.springframework.web.servlet.RequestToViewNameTranslator=org.springframework.web.servlet.view.DefaultRequestToViewNameTranslatororg.springframework.web.servlet.ViewResolver=org.springframework.web.servlet.view.InternalResourceViewResolverorg.springframework.web.servlet.FlashMapManager=org.springframework.web.servlet.support.SessionFlashMapManager在 DispatcherServlet.properties 中定義了 HandlerMapping、HandlerAdapter、ViewResolver 等類。它們的獲取邏輯是相似的。通過文件中定義的全限定名,然后調用 Class.forName() 方法去創建對象。
3. DispatcherServlet 處理流程
以 get 請求為例。當發送 get 請求時,由 FrameworkServlet # doGet 方法進行處理。
FrameworkServlet # doGet
@Override protected final void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {processRequest(request, response); }該方法中又調用了 processRequest() 方法
FrameworkServlet # processRequest
protected final void processRequest(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {long startTime = System.currentTimeMillis();Throwable failureCause = null;// 獲取一個 LocaleContext 對象LocaleContext previousLocaleContext = LocaleContextHolder.getLocaleContext();// 構建一個新的 LocaleContext 對象LocaleContext localeContext = buildLocaleContext(request);// 獲取一個 RequestAttributes 對象RequestAttributes previousAttributes = RequestContextHolder.getRequestAttributes();// 構建一個新的 ServletRequestAttributes 對象ServletRequestAttributes requestAttributes = buildRequestAttributes(request, response, previousAttributes);WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);asyncManager.registerCallableInterceptor(FrameworkServlet.class.getName(), new RequestBindingInterceptor());// 初始化資源持有者// 將 localeContext 保存到 LocaleContextHolder 中// 將 requestAttributes 保存到 RequestContextHolder 中initContextHolders(request, localeContext, requestAttributes);try {doService(request, response);}catch (ServletException | IOException ex) {failureCause = ex;throw ex;}catch (Throwable ex) {failureCause = ex;throw new NestedServletException("Request processing failed", ex);}finally {resetContextHolders(request, previousLocaleContext, previousAttributes);if (requestAttributes != null) {requestAttributes.requestCompleted();}logResult(request, response, failureCause, asyncManager);publishRequestHandledEvent(request, response, startTime, failureCause);} }該方法中新建了一個 LocaleContext 對象和一個 ServletRequestAttributes 對象,并保存到了 LocaleContextHolder 與 RequestContextHolder 中。尤其是 RequestContextHolder 對象,我們可以通過它去獲取 HttpServletRequest、HttpServletResponse 等對象。最后調用了 doService() 方法。
DispatcherServlet # doService
@Override protected void doService(HttpServletRequest request, HttpServletResponse response) throws Exception {logRequest(request);// 保留 request attributes 的快照Map<String, Object> attributesSnapshot = null;if (WebUtils.isIncludeRequest(request)) {attributesSnapshot = new HashMap<>();Enumeration<?> attrNames = request.getAttributeNames();while (attrNames.hasMoreElements()) {String attrName = (String) attrNames.nextElement();if (this.cleanupAfterInclude || attrName.startsWith(DEFAULT_STRATEGIES_PREFIX)) {attributesSnapshot.put(attrName, request.getAttribute(attrName));}}}// Make framework objects available to handlers and view objects.request.setAttribute(WEB_APPLICATION_CONTEXT_ATTRIBUTE, getWebApplicationContext());request.setAttribute(LOCALE_RESOLVER_ATTRIBUTE, this.localeResolver);request.setAttribute(THEME_RESOLVER_ATTRIBUTE, this.themeResolver);request.setAttribute(THEME_SOURCE_ATTRIBUTE, getThemeSource());if (this.flashMapManager != null) {FlashMap inputFlashMap = this.flashMapManager.retrieveAndUpdate(request, response);if (inputFlashMap != null) {request.setAttribute(INPUT_FLASH_MAP_ATTRIBUTE, Collections.unmodifiableMap(inputFlashMap));}request.setAttribute(OUTPUT_FLASH_MAP_ATTRIBUTE, new FlashMap());request.setAttribute(FLASH_MAP_MANAGER_ATTRIBUTE, this.flashMapManager);}try {doDispatch(request, response);}finally {if (!WebAsyncUtils.getAsyncManager(request).isConcurrentHandlingStarted()) {// Restore the original attribute snapshot, in case of an include.if (attributesSnapshot != null) {restoreAttributesAfterInclude(request, attributesSnapshot);}}} }該方法中又調用了 doDispatch() 方法
DispatcherServlet # doDispatch
protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {HttpServletRequest processedRequest = request;HandlerExecutionChain mappedHandler = null;boolean multipartRequestParsed = false;WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);try {ModelAndView mv = null;Exception dispatchException = null;try {// 檢查是否是上傳文件的請求processedRequest = checkMultipart(request);multipartRequestParsed = (processedRequest != request);// 獲取 HandlerExecutionChain // 該方法中確定了用哪個處理器處理當前請求// 并添加了攔截器mappedHandler = getHandler(processedRequest);// 沒有找到合適的處理器if (mappedHandler == null) {noHandlerFound(processedRequest, response);return;}// 獲取 HandlerAdapterHandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());// 獲取請求方法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;}}// 執行攔截器的前置處理if (!mappedHandler.applyPreHandle(processedRequest, response)) {return;}// 處理請求并返回 ModelAndView 對象mv = ha.handle(processedRequest, response, mappedHandler.getHandler());if (asyncManager.isConcurrentHandlingStarted()) {return;}applyDefaultViewName(processedRequest, mv);// 執行攔截器的后置處理mappedHandler.applyPostHandle(processedRequest, response, mv);}catch (Exception ex) {dispatchException = ex;}catch (Throwable err) {dispatchException = new NestedServletException("Handler dispatch failed", err);}// 處理最終的結果processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);}catch (Exception ex) {triggerAfterCompletion(processedRequest, response, mappedHandler, ex);}catch (Throwable err) {triggerAfterCompletion(processedRequest, response, mappedHandler,new NestedServletException("Handler processing failed", err));}finally {if (asyncManager.isConcurrentHandlingStarted()) {if (mappedHandler != null) {mappedHandler.applyAfterConcurrentHandlingStarted(processedRequest, response);}}else {if (multipartRequestParsed) {cleanupMultipart(processedRequest);}}} }接下來我們看一下 getHandler() 方法
DispatcherServlet # getHandler
protected HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {if (this.handlerMappings != null) {// 遍歷所有的 HandlerMapping 去獲取 HandlerExecutionChain for (HandlerMapping mapping : this.handlerMappings) {HandlerExecutionChain handler = mapping.getHandler(request);if (handler != null) {return handler;}}}return null; }該方法中遍歷了所有的 HandlerMapping 去獲取 Handler
AbstractHandlerMapping # getHandler
public final HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {// 獲取合適的 HandlerObject handler = getHandlerInternal(request);if (handler == null) {// 沒有找到合適的 Handler,則使用默認的 Handlerhandler = getDefaultHandler();}if (handler == null) {return null;}// 獲取到了該 Handler 的字符串名,則通過字符串名去獲取對應的對象if (handler instanceof String) {String handlerName = (String) handler;handler = obtainApplicationContext().getBean(handlerName);}// 為當前請求添加攔截器HandlerExecutionChain executionChain = getHandlerExecutionChain(handler, request);if (logger.isTraceEnabled()) {logger.trace("Mapped to " + handler);}else if (logger.isDebugEnabled() && !request.getDispatcherType().equals(DispatcherType.ASYNC)) {logger.debug("Mapped to " + executionChain.getHandler());}if (hasCorsConfigurationSource(handler) || CorsUtils.isPreFlightRequest(request)) {CorsConfiguration config = (this.corsConfigurationSource != null ? this.corsConfigurationSource.getCorsConfiguration(request) : null);CorsConfiguration handlerConfig = getCorsConfiguration(handler, request);config = (config != null ? config.combine(handlerConfig) : handlerConfig);executionChain = getCorsHandlerExecutionChain(request, executionChain, config);}return executionChain; }該方法中去獲取合適的 Handler,獲取失敗的話,則會使用默認的 Handler。并為該請求添加攔截器。
RequestMappingInfoHandlerMapping # getHandlerInternal
protected HandlerMethod getHandlerInternal(HttpServletRequest request) throws Exception {request.removeAttribute(PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE);try {return super.getHandlerInternal(request);}finally {ProducesRequestCondition.clearMediaTypesAttribute(request);} }AbstractHandlerMethodMapping # getHandlerInternal
protected HandlerMethod getHandlerInternal(HttpServletRequest request) throws Exception {// 獲取請求路徑String lookupPath = getUrlPathHelper().getLookupPathForRequest(request);request.setAttribute(LOOKUP_PATH, lookupPath);// 加讀鎖this.mappingRegistry.acquireReadLock();try {// 根據請求路徑獲取對應的 HandlerMethod HandlerMethod handlerMethod = lookupHandlerMethod(lookupPath, request);return (handlerMethod != null ? handlerMethod.createWithResolvedBean() : null);}finally {// 釋放讀鎖this.mappingRegistry.releaseReadLock();} }該方法中根據請求路徑去獲取對應的 HandlerMethod
AbstractHandlerMethodMapping # lookupHandlerMethod
protected HandlerMethod lookupHandlerMethod(String lookupPath, HttpServletRequest request) throws Exception {List<Match> matches = new ArrayList<>();// 根據請求路徑獲取對應的映射List<T> directPathMatches = this.mappingRegistry.getMappingsByUrl(lookupPath);if (directPathMatches != null) {// 獲取匹配的映射// 這里面會做一系列的比較// 如:方法名比較、參數比較、請求頭比較等addMatchingMappings(directPathMatches, matches, request);}if (matches.isEmpty()) {// No choice but to go through all mappings...addMatchingMappings(this.mappingRegistry.getMappings().keySet(), matches, request);}// 匹配到合適的方法,則從中找到最匹配的方法if (!matches.isEmpty()) {Match bestMatch = matches.get(0);if (matches.size() > 1) {Comparator<Match> comparator = new MatchComparator(getMappingComparator(request));matches.sort(comparator);bestMatch = matches.get(0);if (logger.isTraceEnabled()) {logger.trace(matches.size() + " matching mappings: " + matches);}if (CorsUtils.isPreFlightRequest(request)) {return PREFLIGHT_AMBIGUOUS_MATCH;}Match secondBestMatch = matches.get(1);if (comparator.compare(bestMatch, secondBestMatch) == 0) {Method m1 = bestMatch.handlerMethod.getMethod();Method m2 = secondBestMatch.handlerMethod.getMethod();String uri = request.getRequestURI();throw new IllegalStateException("Ambiguous handler methods mapped for '" + uri + "': {" + m1 + ", " + m2 + "}");}}request.setAttribute(BEST_MATCHING_HANDLER_ATTRIBUTE, bestMatch.handlerMethod);handleMatch(bestMatch.mapping, lookupPath, request);return bestMatch.handlerMethod;}// 沒有找到合適的方法,返回 nullelse {return handleNoMatch(this.mappingRegistry.getMappings().keySet(), lookupPath, request);} }該方法中會去獲取與請求最匹配的方法,獲取不到則返回 null。
這里就已經獲取完 handler 了,也就是一個 HandlerMethod 對象,比如 TestController # test 。我們往下走。
@Controller public class TestController {@GetMapping("/test")public String test() {return "test";} }DispatcherServlet # getHandlerAdapter
protected HandlerAdapter getHandlerAdapter(Object handler) throws ServletException {if (this.handlerAdapters != null) {for (HandlerAdapter adapter : this.handlerAdapters) {if (adapter.supports(handler)) {return adapter;}}}throw new ServletException("No adapter for handler [" + handler +"]: The DispatcherServlet configuration needs to include a HandlerAdapter that supports this handler"); }該方法就是去找一個對應的 HandlerAdapter,一般是 RequestMappingHandlerAdapter。
AbstractHandlerMethodAdapter # handle
public final ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler)throws Exception {return handleInternal(request, response, (HandlerMethod) handler); }RequestMappingHandlerAdapter # handleInternal
protected ModelAndView handleInternal(HttpServletRequest request,HttpServletResponse response, HandlerMethod handlerMethod) throws Exception {ModelAndView mav;checkRequest(request);// Execute invokeHandlerMethod in synchronized block if required.if (this.synchronizeOnSession) {HttpSession session = request.getSession(false);if (session != null) {Object mutex = WebUtils.getSessionMutex(session);synchronized (mutex) {mav = invokeHandlerMethod(request, response, handlerMethod);}}else {// No HttpSession available -> no mutex necessarymav = invokeHandlerMethod(request, response, handlerMethod);}}else {// No synchronization on session demanded at all...mav = invokeHandlerMethod(request, response, handlerMethod);}if (!response.containsHeader(HEADER_CACHE_CONTROL)) {if (getSessionAttributesHandler(handlerMethod).hasSessionAttributes()) {applyCacheSeconds(response, this.cacheSecondsForSessionAttributeHandlers);}else {prepareResponse(response);}}return mav; }該方法中調用了 invokeHandlerMethod() 方法
RequestMappingHandlerAdapter # invokeHandlerMethod
protected ModelAndView invokeHandlerMethod(HttpServletRequest request,HttpServletResponse response, HandlerMethod handlerMethod) throws Exception {ServletWebRequest webRequest = new ServletWebRequest(request, response);try {// 找到 @InitBinder 標注的方法// @InitBinder 與 WebDatabinder 一起使用,用于注冊自定義的屬性編輯器WebDataBinderFactory binderFactory = getDataBinderFactory(handlerMethod);// 找到 @ModelAttribute 標注的方法ModelFactory modelFactory = getModelFactory(handlerMethod, binderFactory);ServletInvocableHandlerMethod invocableMethod = createInvocableHandlerMethod(handlerMethod);// 注冊參數解析器if (this.argumentResolvers != null) {invocableMethod.setHandlerMethodArgumentResolvers(this.argumentResolvers);}// 注冊返回值解析器if (this.returnValueHandlers != null) {invocableMethod.setHandlerMethodReturnValueHandlers(this.returnValueHandlers);}invocableMethod.setDataBinderFactory(binderFactory);// 注冊參數名發現器invocableMethod.setParameterNameDiscoverer(this.parameterNameDiscoverer);ModelAndViewContainer mavContainer = new ModelAndViewContainer();mavContainer.addAllAttributes(RequestContextUtils.getInputFlashMap(request));// 調用 @ModelAttribute 標注的方法,保證它在其他方法執行前先被執行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()) {Object result = asyncManager.getConcurrentResult();mavContainer = (ModelAndViewContainer) asyncManager.getConcurrentResultContext()[0];asyncManager.clearConcurrentResult();LogFormatUtils.traceDebug(logger, traceOn -> {String formatted = LogFormatUtils.formatValue(result, !traceOn);return "Resume with async result [" + formatted + "]";});invocableMethod = invocableMethod.wrapConcurrentResult(result);}// 調用該方法invocableMethod.invokeAndHandle(webRequest, mavContainer);if (asyncManager.isConcurrentHandlingStarted()) {return null;}// 返回 ModelAndView 對象return getModelAndView(mavContainer, modelFactory, webRequest);}finally {webRequest.requestCompleted();} }該方法中會找到并注冊 @InitBinder 標注的方法,找到并調用 @ModelAttribute 標注的的方法。調用 invokeAndHandleI() 方法,最終返回 ModelAndView 對象
ServletInvocableHandlerMethod # invokeAndHandle
public void invokeAndHandle(ServletWebRequest webRequest, ModelAndViewContainer mavContainer,Object... providedArgs) throws Exception {// 調用方法并獲取返回值Object returnValue = invokeForRequest(webRequest, mavContainer, providedArgs);setResponseStatus(webRequest);if (returnValue == null) {if (isRequestNotModified(webRequest) || getResponseStatus() != null || mavContainer.isRequestHandled()) {disableContentCachingIfNecessary(webRequest);mavContainer.setRequestHandled(true);return;}}else if (StringUtils.hasText(getResponseStatusReason())) {mavContainer.setRequestHandled(true);return;}mavContainer.setRequestHandled(false);Assert.state(this.returnValueHandlers != null, "No return value handlers");try {// 使用對應的 HandlerMethodReturnValueHandler 去處理返回值this.returnValueHandlers.handleReturnValue(returnValue, getReturnValueType(returnValue), mavContainer, webRequest);}catch (Exception ex) {if (logger.isTraceEnabled()) {logger.trace(formatErrorForReturnValue(returnValue), ex);}throw ex;} }InvocableHandlerMethod # invokeForRequest
public Object invokeForRequest(NativeWebRequest request, @Nullable ModelAndViewContainer mavContainer,Object... providedArgs) throws Exception {// 獲取形參值Object[] args = getMethodArgumentValues(request, mavContainer, providedArgs);if (logger.isTraceEnabled()) {logger.trace("Arguments: " + Arrays.toString(args));}// 調用方法return doInvoke(args); }InvocableHandlerMethod # getMethodArgumentValues
protected Object[] getMethodArgumentValues(NativeWebRequest request, @Nullable ModelAndViewContainer mavContainer,Object... providedArgs) throws Exception {// 獲取 MethodParameter 數組MethodParameter[] parameters = getMethodParameters();if (ObjectUtils.isEmpty(parameters)) {return EMPTY_ARGS;}Object[] args = new Object[parameters.length];for (int i = 0; i < parameters.length; i++) {MethodParameter parameter = parameters[i];parameter.initParameterNameDiscovery(this.parameterNameDiscoverer);args[i] = findProvidedArgument(parameter, providedArgs);if (args[i] != null) {continue;}if (!this.resolvers.supportsParameter(parameter)) {throw new IllegalStateException(formatArgumentError(parameter, "No suitable resolver"));}try {// 解析參數args[i] = this.resolvers.resolveArgument(parameter, mavContainer, request, this.dataBinderFactory);}catch (Exception ex) {// Leave stack trace for later, exception may actually be resolved and handled...if (logger.isDebugEnabled()) {String exMsg = ex.getMessage();if (exMsg != null && !exMsg.contains(parameter.getExecutable().toGenericString())) {logger.debug(formatArgumentError(parameter, exMsg));}}throw ex;}}return args; }該方法中調用了 resolveArgument() 去解析參數
HandlerMethodArgumentResolverComposite # resolveArgument
public Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer,NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory) throws Exception {// 獲取 HandlerMethodArgumentResolver -> RequestParamMethodArgumentResolverHandlerMethodArgumentResolver resolver = getArgumentResolver(parameter);if (resolver == null) {throw new IllegalArgumentException("Unsupported parameter type [" +parameter.getParameterType().getName() + "]. supportsParameter should be called first.");}// 解析參數return resolver.resolveArgument(parameter, mavContainer, webRequest, binderFactory); }AbstractNamedValueMethodArgumentResolver # resolveArgument
public final Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer,NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory) throws Exception {NamedValueInfo namedValueInfo = getNamedValueInfo(parameter);MethodParameter nestedParameter = parameter.nestedIfOptional();Object resolvedName = resolveEmbeddedValuesAndExpressions(namedValueInfo.name);if (resolvedName == null) {throw new IllegalArgumentException("Specified name must not resolve to null: [" + namedValueInfo.name + "]");}Object arg = resolveName(resolvedName.toString(), nestedParameter, webRequest);if (arg == null) {if (namedValueInfo.defaultValue != null) {arg = resolveEmbeddedValuesAndExpressions(namedValueInfo.defaultValue);}else if (namedValueInfo.required && !nestedParameter.isOptional()) {handleMissingValue(namedValueInfo.name, nestedParameter, webRequest);}arg = handleNullValue(namedValueInfo.name, arg, nestedParameter.getNestedParameterType());}else if ("".equals(arg) && namedValueInfo.defaultValue != null) {arg = resolveEmbeddedValuesAndExpressions(namedValueInfo.defaultValue);}if (binderFactory != null) {WebDataBinder binder = binderFactory.createBinder(webRequest, null, namedValueInfo.name);try {arg = binder.convertIfNecessary(arg, parameter.getParameterType(), parameter);}catch (ConversionNotSupportedException ex) {throw new MethodArgumentConversionNotSupportedException(arg, ex.getRequiredType(),namedValueInfo.name, parameter, ex.getCause());}catch (TypeMismatchException ex) {throw new MethodArgumentTypeMismatchException(arg, ex.getRequiredType(),namedValueInfo.name, parameter, ex.getCause());}}handleResolvedValue(arg, namedValueInfo.name, parameter, mavContainer, webRequest);return arg; }AbstractNamedValueMethodArgumentResolver # getNamedValueInfo
private NamedValueInfo getNamedValueInfo(MethodParameter parameter) {// 先從緩存中獲取NamedValueInfo namedValueInfo = this.namedValueInfoCache.get(parameter);// 緩存中獲取不到if (namedValueInfo == null) {// 獲取 @RequestParam 中的 value 屬性值,如果有,則將參數名設置為該值namedValueInfo = createNamedValueInfo(parameter);// 如果沒有使用 @RequestParam 注解或使用了但沒有設置 value 屬性// 則使用 ASM 框架去獲取字節碼來獲取屬性名namedValueInfo = updateNamedValueInfo(parameter, namedValueInfo);this.namedValueInfoCache.put(parameter, namedValueInfo);}return namedValueInfo; }RequestParamMethodArgumentResolver # createNamedValueInfo
protected NamedValueInfo createNamedValueInfo(MethodParameter parameter) {// 根據 @RequestParam 注解去創建 NamedValueInfo // 如果 @RequestParam 中的 value 屬性有值,則設置參數名為該值RequestParam ann = parameter.getParameterAnnotation(RequestParam.class);return (ann != null ? new RequestParamNamedValueInfo(ann) : new RequestParamNamedValueInfo()); }AbstractNamedValueMethodArgumentResolver # updateNamedValueInfo
private NamedValueInfo updateNamedValueInfo(MethodParameter parameter, NamedValueInfo info) {String name = info.name;if (info.name.isEmpty()) {name = parameter.getParameterName();if (name == null) {throw new IllegalArgumentException("Name for argument of type [" + parameter.getNestedParameterType().getName() +"] not specified, and parameter name information not found in class file either.");}}String defaultValue = (ValueConstants.DEFAULT_NONE.equals(info.defaultValue) ? null : info.defaultValue);return new NamedValueInfo(name, info.required, defaultValue); }MethodParameter # getParameterName
public String getParameterName() {if (this.parameterIndex < 0) {return null;}ParameterNameDiscoverer discoverer = this.parameterNameDiscoverer;if (discoverer != null) {String[] parameterNames = null;if (this.executable instanceof Method) {parameterNames = discoverer.getParameterNames((Method) this.executable);}else if (this.executable instanceof Constructor) {parameterNames = discoverer.getParameterNames((Constructor<?>) this.executable);}if (parameterNames != null) {this.parameterName = parameterNames[this.parameterIndex];}this.parameterNameDiscoverer = null;}return this.parameterName; }LocalVariableTableParameterNameDiscoverer # getParameterNames
public String[] getParameterNames(Method method) {Method originalMethod = BridgeMethodResolver.findBridgedMethod(method);return doGetParameterNames(originalMethod); }LocalVariableTableParameterNameDiscoverer # doGetParameterNames
private String[] doGetParameterNames(Executable executable) {Class<?> declaringClass = executable.getDeclaringClass();Map<Executable, String[]> map = this.parameterNamesCache.computeIfAbsent(declaringClass, this::inspectClass);return (map != NO_DEBUG_INFO_MAP ? map.get(executable) : null); }LocalVariableTableParameterNameDiscoverer # inspectClass
private Map<Executable, String[]> inspectClass(Class<?> clazz) {// 獲取字節碼文件InputStream is = clazz.getResourceAsStream(ClassUtils.getClassFileName(clazz));if (is == null) {if (logger.isDebugEnabled()) {logger.debug("Cannot find '.class' file for class [" + clazz +"] - unable to determine constructor/method parameter names");}return NO_DEBUG_INFO_MAP;}try {ClassReader classReader = new ClassReader(is);Map<Executable, String[]> map = new ConcurrentHashMap<>(32);// ASM 框架提升字節碼文件classReader.accept(new ParameterNameDiscoveringVisitor(clazz, map), 0);return map;}catch (IOException ex) {if (logger.isDebugEnabled()) {logger.debug("Exception thrown while reading '.class' file for class [" + clazz +"] - unable to determine constructor/method parameter names", ex);}}catch (IllegalArgumentException ex) {if (logger.isDebugEnabled()) {logger.debug("ASM ClassReader failed to parse class file [" + clazz +"], probably due to a new Java class file version that isn't supported yet " +"- unable to determine constructor/method parameter names", ex);}}finally {try {is.close();}catch (IOException ex) {}}return NO_DEBUG_INFO_MAP; }走到這一步便是通過 ASM 框架來提升字節碼文件獲取參數名稱了。所以推薦使用 @ReuquestParam 并設置 value 屬性值,這樣可以直接獲取到參數名,避免了 ASM 框架編輯字節碼所帶來的性能消耗。
DispatcherServlet # processDispatchResult
private void processDispatchResult(HttpServletRequest request, HttpServletResponse response,@Nullable HandlerExecutionChain mappedHandler, @Nullable ModelAndView mv,@Nullable Exception exception) throws Exception {boolean errorView = false;if (exception != null) {if (exception instanceof ModelAndViewDefiningException) {logger.debug("ModelAndViewDefiningException encountered", exception);mv = ((ModelAndViewDefiningException) exception).getModelAndView();}else {Object handler = (mappedHandler != null ? mappedHandler.getHandler() : null);mv = processHandlerException(request, response, handler, exception);errorView = (mv != null);}}if (mv != null && !mv.wasCleared()) {// 渲染 ModelAndViewrender(mv, request, response);if (errorView) {WebUtils.clearErrorRequestAttributes(request);}}else {if (logger.isTraceEnabled()) {logger.trace("No view rendering, null ModelAndView returned.");}}if (WebAsyncUtils.getAsyncManager(request).isConcurrentHandlingStarted()) {// Concurrent handling started during a forwardreturn;}if (mappedHandler != null) {// Exception (if any) is already handled..mappedHandler.triggerAfterCompletion(request, response, null);} }本方法中調用了 render() 方法去渲染視圖
DispatcherServlet # render
protected void render(ModelAndView mv, HttpServletRequest request, HttpServletResponse response) throws Exception {Locale locale =(this.localeResolver != null ? this.localeResolver.resolveLocale(request) : request.getLocale());response.setLocale(locale);View view;String viewName = mv.getViewName();if (viewName != null) {// 根據 viewName 解析出 Viewview = resolveViewName(viewName, mv.getModelInternal(), locale, request);if (view == null) {throw new ServletException("Could not resolve view with name '" + mv.getViewName() +"' in servlet with name '" + getServletName() + "'");}}else {// No need to lookup: the ModelAndView object contains the actual View object.view = mv.getView();if (view == null) {throw new ServletException("ModelAndView [" + mv + "] neither contains a view name nor a " +"View object in servlet with name '" + getServletName() + "'");}}// Delegate to the View object for rendering.if (logger.isTraceEnabled()) {logger.trace("Rendering view [" + view + "] ");}try {if (mv.getStatus() != null) {response.setStatus(mv.getStatus().value());}view.render(mv.getModelInternal(), request, response);}catch (Exception ex) {if (logger.isDebugEnabled()) {logger.debug("Error rendering view [" + view + "]", ex);}throw ex;} }本方法中調用了 resolveViewName() 去獲取 View
DispatcherServlet # resolveViewName
protected View resolveViewName(String viewName, @Nullable Map<String, Object> model,Locale locale, HttpServletRequest request) throws Exception {if (this.viewResolvers != null) {for (ViewResolver viewResolver : this.viewResolvers) {// 使用 ViewResolver 去解析出 ViewView view = viewResolver.resolveViewName(viewName, locale);if (view != null) {return view;}}}return null; }本方法中找到合適的 ViewResolver 去解析出 View
public View resolveViewName(String viewName, Locale locale) throws Exception {// 是否啟用了緩存功能,默認啟用了if (!isCache()) {return createView(viewName, locale);}else {// 先嘗試從緩存中取 ViewObject cacheKey = getCacheKey(viewName, locale);View view = this.viewAccessCache.get(cacheKey);if (view == null) {synchronized (this.viewCreationCache) {view = this.viewCreationCache.get(cacheKey);if (view == null) {// 緩存中沒有去到,交給子類去創建 Viewview = createView(viewName, locale);if (view == null && this.cacheUnresolved) {view = UNRESOLVED_VIEW;}if (view != null && this.cacheFilter.filter(view, viewName, locale)) {this.viewAccessCache.put(cacheKey, view);this.viewCreationCache.put(cacheKey, view);}}}}else {if (logger.isTraceEnabled()) {logger.trace(formatKey(cacheKey) + "served from cache");}}return (view != UNRESOLVED_VIEW ? view : null);} }本方法中判斷是否開啟了視圖緩存功能,默認是開啟了的。先嘗試從緩存中取 View,取不到的話則交給子類去創建 View。
UrlBasedViewResolver # createView
@Override protected View createView(String viewName, Locale locale) throws Exception {// 判斷該視圖解析器是否能處理這個視圖// 如果不能的話,交給其他視圖解析器去處理if (!canHandle(viewName, locale)) {return null;}// 檢查前綴是否為 "redirect:"// 有的話則是請求重定向if (viewName.startsWith(REDIRECT_URL_PREFIX)) {// 截取 "redirect:" 后的字符串String redirectUrl = viewName.substring(REDIRECT_URL_PREFIX.length());// 創建重定視圖RedirectView view = new RedirectView(redirectUrl,isRedirectContextRelative(), isRedirectHttp10Compatible());String[] hosts = getRedirectHosts();if (hosts != null) {view.setHosts(hosts);}return applyLifecycleMethods(REDIRECT_URL_PREFIX, view);}// 檢查前綴是否為 "forward:"// 有的話則是請求轉發if (viewName.startsWith(FORWARD_URL_PREFIX)) {String forwardUrl = viewName.substring(FORWARD_URL_PREFIX.length());InternalResourceView view = new InternalResourceView(forwardUrl);return applyLifecycleMethods(FORWARD_URL_PREFIX, view);}// 如果沒有加這兩個前綴的話,則回調給父類處理// 其實最終的處理結果是跟請求轉發一樣的return super.createView(viewName, locale); }該方法中會獲取字符串前綴。前綴為 “redirect:” 則是請求重定向,為 “forward:” 則是請求轉發。如果沒有這兩個前綴的話,又回調到父類 AbstractCachingViewResolver # createView 方法中。
AbstractCachingViewResolver # createView
protected View createView(String viewName, Locale locale) throws Exception {return loadView(viewName, locale); }回調到父類 AbstractCachingViewResolver # createView 方法,并調用了 loadView() 方法
InternalResourceViewResolver # buildView
protected AbstractUrlBasedView buildView(String viewName) throws Exception {// 可以看到,這里創建的 View 類型跟請求轉發的相同InternalResourceView view = (InternalResourceView) super.buildView(viewName);if (this.alwaysInclude != null) {view.setAlwaysInclude(this.alwaysInclude);}view.setPreventDispatchLoop(true);return view; }本方法中調用了 buildView() 方法創建 View,可以看到,這里創建的 View 類型跟請求轉發的相同
UrlBasedViewResolver # buildView
protected AbstractUrlBasedView buildView(String viewName) throws Exception {Class<?> viewClass = getViewClass();Assert.state(viewClass != null, "No view class");AbstractUrlBasedView view = (AbstractUrlBasedView) BeanUtils.instantiateClass(viewClass);// 拼接上前綴和后綴// 可以從 web.xml 文件中獲取view.setUrl(getPrefix() + viewName + getSuffix());view.setAttributesMap(getAttributesMap());String contentType = getContentType();if (contentType != null) {view.setContentType(contentType);}String requestContextAttribute = getRequestContextAttribute();if (requestContextAttribute != null) {view.setRequestContextAttribute(requestContextAttribute);}Boolean exposePathVariables = getExposePathVariables();if (exposePathVariables != null) {view.setExposePathVariables(exposePathVariables);}Boolean exposeContextBeansAsAttributes = getExposeContextBeansAsAttributes();if (exposeContextBeansAsAttributes != null) {view.setExposeContextBeansAsAttributes(exposeContextBeansAsAttributes);}String[] exposedContextBeanNames = getExposedContextBeanNames();if (exposedContextBeanNames != null) {view.setExposedContextBeanNames(exposedContextBeanNames);}return view; }本方法中將 viewName 拼接了前綴和后綴,獲取到的便是最終的完整路徑。這里并將 View 獲取成功了。
AbstractView # render
public void render(@Nullable Map<String, ?> model, HttpServletRequest request,HttpServletResponse response) throws Exception {if (logger.isDebugEnabled()) {logger.debug("View " + formatViewName() +", model " + (model != null ? model : Collections.emptyMap()) +(this.staticAttributes.isEmpty() ? "" : ", static attributes " + this.staticAttributes));}// 創建并合并屬性到 Map 中// 如:保存到 ModelAndView 或 Model 中的屬性Map<String, Object> mergedModel = createMergedOutputModel(model, request, response);// 準備好 HttpServletResponse 對象prepareResponse(request, response);// 解析出視圖renderMergedOutputModel(mergedModel, getRequestToExpose(request), response); }該方法中主要是將我們自己保存到 ModelAndView 或 Model 中的屬性轉換為 Map 對象。最后調用 renderMergedOutputModel() 方法。
InternalResourceView # renderMergedOutputModel
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {// 將屬性保存到 request 域中exposeModelAsRequestAttributes(model, request);// Expose helpers as request attributes, if any.exposeHelpers(request);// 確定請求的 urlString dispatcherPath = prepareForRendering(request, response);// 獲取一個請求轉發器RequestDispatcher rd = getRequestDispatcher(request, dispatcherPath);if (rd == null) {throw new ServletException("Could not get RequestDispatcher for [" + getUrl() +"]: Check that the corresponding file exists within your web application archive!");}// 是一個 include 請求,jsp 中經常用到,實現 jsp 頁面的復用if (useInclude(request, response)) {response.setContentType(getContentType());if (logger.isDebugEnabled()) {logger.debug("Including [" + getUrl() + "]");}rd.include(request, response);}else {if (logger.isDebugEnabled()) {logger.debug("Forwarding to [" + getUrl() + "]");}// 請求轉發rd.forward(request, response);} }4. 總結
SpringMVC 處理請求的大致流程就是這樣了。內容有點多,建議最好還是自己 debug 走一遍代碼,梳理出整個脈絡才好。
總結
以上是生活随笔為你收集整理的SpringMVC 执行流程解析的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Debug Tensorflow :Tw
- 下一篇: 目标检测:Yolov5集百家之长