Servlet和springMVC

打印 上一主题 下一主题

主题 969|帖子 969|积分 2907

什么是Servlet?


  • Servlet是使用Java语言编写的运行在服务器端的程序。狭义的Servlet是指Java语言实现的一个接口,广义的Servlet是指任何实现了这个Servlet接口的类,一般情况下,人们将Servlet理解为后者。Servlet 主要用于处理客户端传来的 HTTP 请求,并返回一个响应,它能够处理的请求有doGet()和doPost()等方法
  • Servlet由Servlet容器提供,所谓的Servlet容器是指提供了Servlet 功能的服务器(本书中指Tomcat),Servlet容器将Servlet动态地加载到服务器上。与HTTP 协议相关的Servlet使用HTTP请求和HTTP响应与客户端进行交互。因此,Servlet容器支持所有HTTP协议的请求和响应。Servlet应用程序的体系结构如图所示。

什么是SpringMVC?


  • Spring MVC一开始就定位于一个较为松散的组合,展示给用户的视图(View)、控制器返回的数据模型(Model)、定位视图的视图解析器(ViewResolver)和处理适配器(HandlerAdapter)等内容都是独立的。换句话说,通过Spring MVC很容易把后台的数据转换为各种类型的数据,以满足移动互联网数据多样化的要求。例如,Spring MVC可以十分方便地转换为目前最常用的JSON数据集,也可以转换为PDF、Excel和XML等。加之Spring MVC是基于Spring基础框架派生出来的Web框架,所以它天然就可以十分方便地整合到Spring框架中,而Spring整合Struts2还是比较繁复的.
  • mvc架构设计:处理请求先到达控制器(Controller),控制器的作用是进行请求分发,这样它会根据请求的内容去访问模型层(Model);在现今互联网系统中,数据主要从数据库和NoSQL中来,而且对于数据库而言往往还存在事务的机制,为了适应这样的变化,设计者会把模型层再细分为两层,即服务层(Service)和数据访问层(DAO);当控制器获取到由模型层返回的数据后,就将数据渲染到视图中,这样就能够展现给用户了
  •  
     图取自于书籍
 
思考和疑问

早些年的时候,使用servlet开发web程序, 一般都是继承HttpServlet接口,请求访问时直接根据类名调用.但这样写的结果是,一个类只能处理一个请求.项目结构大概长这样

使用SpringMVC框架后,只需要配置简单的@RequestMapping("")就可以找到对应的方法,原来的servlet呢? 对springMVC的了解还是不够详细,所以
继续探讨以下几个问题
1.SpringMVC如何代替Servlet?


 
 
 可以看到DispatcherServlet继承自HttpServlet,  前端控制器其实就相当于一个Servlet.
 2. SpringMVC的工作流程?


 
图取自于书籍
基于springboot开发使得SpringMVC的使用更为简便,可以通过Spring Boot的配置来定制这些组件的初始化

    1. /*
    2. * Copyright 2002-2019 the original author or authors.
    3. *
    4. * Licensed under the Apache License, Version 2.0 (the "License");
    5. * you may not use this file except in compliance with the License.
    6. * You may obtain a copy of the License at
    7. *
    8. *      https://www.apache.org/licenses/LICENSE-2.0
    9. *
    10. * Unless required by applicable law or agreed to in writing, software
    11. * distributed under the License is distributed on an "AS IS" BASIS,
    12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13. * See the License for the specific language governing permissions and
    14. * limitations under the License.
    15. */
    16. package org.springframework.web.servlet;
    17. import java.io.IOException;
    18. import java.util.ArrayList;
    19. import java.util.Arrays;
    20. import java.util.Collections;
    21. import java.util.Enumeration;
    22. import java.util.HashMap;
    23. import java.util.HashSet;
    24. import java.util.LinkedList;
    25. import java.util.List;
    26. import java.util.Locale;
    27. import java.util.Map;
    28. import java.util.Properties;
    29. import java.util.Set;
    30. import java.util.stream.Collectors;
    31. import javax.servlet.DispatcherType;
    32. import javax.servlet.ServletContext;
    33. import javax.servlet.ServletException;
    34. import javax.servlet.http.HttpServletRequest;
    35. import javax.servlet.http.HttpServletResponse;
    36. import org.apache.commons.logging.Log;
    37. import org.apache.commons.logging.LogFactory;
    38. import org.springframework.beans.factory.BeanFactoryUtils;
    39. import org.springframework.beans.factory.BeanInitializationException;
    40. import org.springframework.beans.factory.NoSuchBeanDefinitionException;
    41. import org.springframework.context.ApplicationContext;
    42. import org.springframework.context.ConfigurableApplicationContext;
    43. import org.springframework.context.i18n.LocaleContext;
    44. import org.springframework.core.annotation.AnnotationAwareOrderComparator;
    45. import org.springframework.core.io.ClassPathResource;
    46. import org.springframework.core.io.support.PropertiesLoaderUtils;
    47. import org.springframework.core.log.LogFormatUtils;
    48. import org.springframework.http.server.ServletServerHttpRequest;
    49. import org.springframework.lang.Nullable;
    50. import org.springframework.ui.context.ThemeSource;
    51. import org.springframework.util.ClassUtils;
    52. import org.springframework.util.StringUtils;
    53. import org.springframework.web.context.WebApplicationContext;
    54. import org.springframework.web.context.request.ServletWebRequest;
    55. import org.springframework.web.context.request.async.WebAsyncManager;
    56. import org.springframework.web.context.request.async.WebAsyncUtils;
    57. import org.springframework.web.multipart.MultipartException;
    58. import org.springframework.web.multipart.MultipartHttpServletRequest;
    59. import org.springframework.web.multipart.MultipartResolver;
    60. import org.springframework.web.util.NestedServletException;
    61. import org.springframework.web.util.WebUtils;
    62. /**
    63. * Central dispatcher for HTTP request handlers/controllers, e.g. for web UI controllers
    64. * or HTTP-based remote service exporters. Dispatches to registered handlers for processing
    65. * a web request, providing convenient mapping and exception handling facilities.
    66. *
    67. * <p>This servlet is very flexible: It can be used with just about any workflow, with the
    68. * installation of the appropriate adapter classes. It offers the following functionality
    69. * that distinguishes it from other request-driven web MVC frameworks:
    70. *
    71. * <ul>
    72. * <li>It is based around a JavaBeans configuration mechanism.
    73. *
    74. * <li>It can use any {@link HandlerMapping} implementation - pre-built or provided as part
    75. * of an application - to control the routing of requests to handler objects. Default is
    76. * {@link org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping} and
    77. * {@link org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping}.
    78. * HandlerMapping objects can be defined as beans in the servlet's application context,
    79. * implementing the HandlerMapping interface, overriding the default HandlerMapping if
    80. * present. HandlerMappings can be given any bean name (they are tested by type).
    81. *
    82. * <li>It can use any {@link HandlerAdapter}; this allows for using any handler interface.
    83. * Default adapters are {@link org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter},
    84. * {@link org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter}, for Spring's
    85. * {@link org.springframework.web.HttpRequestHandler} and
    86. * {@link org.springframework.web.servlet.mvc.Controller} interfaces, respectively. A default
    87. * {@link org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter}
    88. * will be registered as well. HandlerAdapter objects can be added as beans in the
    89. * application context, overriding the default HandlerAdapters. Like HandlerMappings,
    90. * HandlerAdapters can be given any bean name (they are tested by type).
    91. *
    92. * <li>The dispatcher's exception resolution strategy can be specified via a
    93. * {@link HandlerExceptionResolver}, for example mapping certain exceptions to error pages.
    94. * Default are
    95. * {@link org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver},
    96. * {@link org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver}, and
    97. * {@link org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver}.
    98. * These HandlerExceptionResolvers can be overridden through the application context.
    99. * HandlerExceptionResolver can be given any bean name (they are tested by type).
    100. *
    101. * <li>Its view resolution strategy can be specified via a {@link ViewResolver}
    102. * implementation, resolving symbolic view names into View objects. Default is
    103. * {@link org.springframework.web.servlet.view.InternalResourceViewResolver}.
    104. * ViewResolver objects can be added as beans in the application context, overriding the
    105. * default ViewResolver. ViewResolvers can be given any bean name (they are tested by type).
    106. *
    107. * <li>If a {@link View} or view name is not supplied by the user, then the configured
    108. * {@link RequestToViewNameTranslator} will translate the current request into a view name.
    109. * The corresponding bean name is "viewNameTranslator"; the default is
    110. * {@link org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator}.
    111. *
    112. * <li>The dispatcher's strategy for resolving multipart requests is determined by a
    113. * {@link org.springframework.web.multipart.MultipartResolver} implementation.
    114. * Implementations for Apache Commons FileUpload and Servlet 3 are included; the typical
    115. * choice is {@link org.springframework.web.multipart.commons.CommonsMultipartResolver}.
    116. * The MultipartResolver bean name is "multipartResolver"; default is none.
    117. *
    118. * <li>Its locale resolution strategy is determined by a {@link LocaleResolver}.
    119. * Out-of-the-box implementations work via HTTP accept header, cookie, or session.
    120. * The LocaleResolver bean name is "localeResolver"; default is
    121. * {@link org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver}.
    122. *
    123. * <li>Its theme resolution strategy is determined by a {@link ThemeResolver}.
    124. * Implementations for a fixed theme and for cookie and session storage are included.
    125. * The ThemeResolver bean name is "themeResolver"; default is
    126. * {@link org.springframework.web.servlet.theme.FixedThemeResolver}.
    127. * </ul>
    128. *
    129. * <p><b>NOTE: The {@code @RequestMapping} annotation will only be processed if a
    130. * corresponding {@code HandlerMapping} (for type-level annotations) and/or
    131. * {@code HandlerAdapter} (for method-level annotations) is present in the dispatcher.</b>
    132. * This is the case by default. However, if you are defining custom {@code HandlerMappings}
    133. * or {@code HandlerAdapters}, then you need to make sure that a corresponding custom
    134. * {@code RequestMappingHandlerMapping} and/or {@code RequestMappingHandlerAdapter}
    135. * is defined as well - provided that you intend to use {@code @RequestMapping}.
    136. *
    137. * <p><b>A web application can define any number of DispatcherServlets.</b>
    138. * Each servlet will operate in its own namespace, loading its own application context
    139. * with mappings, handlers, etc. Only the root application context as loaded by
    140. * {@link org.springframework.web.context.ContextLoaderListener}, if any, will be shared.
    141. *
    142. * <p>As of Spring 3.1, {@code DispatcherServlet} may now be injected with a web
    143. * application context, rather than creating its own internally. This is useful in Servlet
    144. * 3.0+ environments, which support programmatic registration of servlet instances.
    145. * See the {@link #DispatcherServlet(WebApplicationContext)} javadoc for details.
    146. *
    147. * @author Rod Johnson
    148. * @author Juergen Hoeller
    149. * @author Rob Harrop
    150. * @author Chris Beams
    151. * @author Rossen Stoyanchev
    152. * @see org.springframework.web.HttpRequestHandler
    153. * @see org.springframework.web.servlet.mvc.Controller
    154. * @see org.springframework.web.context.ContextLoaderListener
    155. */
    156. @SuppressWarnings("serial")
    157. public class DispatcherServlet extends FrameworkServlet {
    158.     /** Well-known name for the MultipartResolver object in the bean factory for this namespace. */
    159.     public static final String MULTIPART_RESOLVER_BEAN_NAME = "multipartResolver";
    160.     /** Well-known name for the LocaleResolver object in the bean factory for this namespace. */
    161.     public static final String LOCALE_RESOLVER_BEAN_NAME = "localeResolver";
    162.     /** Well-known name for the ThemeResolver object in the bean factory for this namespace. */
    163.     public static final String THEME_RESOLVER_BEAN_NAME = "themeResolver";
    164.     /**
    165.      * Well-known name for the HandlerMapping object in the bean factory for this namespace.
    166.      * Only used when "detectAllHandlerMappings" is turned off.
    167.      * @see #setDetectAllHandlerMappings
    168.      */
    169.     public static final String HANDLER_MAPPING_BEAN_NAME = "handlerMapping";
    170.     /**
    171.      * Well-known name for the HandlerAdapter object in the bean factory for this namespace.
    172.      * Only used when "detectAllHandlerAdapters" is turned off.
    173.      * @see #setDetectAllHandlerAdapters
    174.      */
    175.     public static final String HANDLER_ADAPTER_BEAN_NAME = "handlerAdapter";
    176.     /**
    177.      * Well-known name for the HandlerExceptionResolver object in the bean factory for this namespace.
    178.      * Only used when "detectAllHandlerExceptionResolvers" is turned off.
    179.      * @see #setDetectAllHandlerExceptionResolvers
    180.      */
    181.     public static final String HANDLER_EXCEPTION_RESOLVER_BEAN_NAME = "handlerExceptionResolver";
    182.     /**
    183.      * Well-known name for the RequestToViewNameTranslator object in the bean factory for this namespace.
    184.      */
    185.     public static final String REQUEST_TO_VIEW_NAME_TRANSLATOR_BEAN_NAME = "viewNameTranslator";
    186.     /**
    187.      * Well-known name for the ViewResolver object in the bean factory for this namespace.
    188.      * Only used when "detectAllViewResolvers" is turned off.
    189.      * @see #setDetectAllViewResolvers
    190.      */
    191.     public static final String VIEW_RESOLVER_BEAN_NAME = "viewResolver";
    192.     /**
    193.      * Well-known name for the FlashMapManager object in the bean factory for this namespace.
    194.      */
    195.     public static final String FLASH_MAP_MANAGER_BEAN_NAME = "flashMapManager";
    196.     /**
    197.      * Request attribute to hold the current web application context.
    198.      * Otherwise only the global web app context is obtainable by tags etc.
    199.      * @see org.springframework.web.servlet.support.RequestContextUtils#findWebApplicationContext
    200.      */
    201.     public static final String WEB_APPLICATION_CONTEXT_ATTRIBUTE = DispatcherServlet.class.getName() + ".CONTEXT";
    202.     /**
    203.      * Request attribute to hold the current LocaleResolver, retrievable by views.
    204.      * @see org.springframework.web.servlet.support.RequestContextUtils#getLocaleResolver
    205.      */
    206.     public static final String LOCALE_RESOLVER_ATTRIBUTE = DispatcherServlet.class.getName() + ".LOCALE_RESOLVER";
    207.     /**
    208.      * Request attribute to hold the current ThemeResolver, retrievable by views.
    209.      * @see org.springframework.web.servlet.support.RequestContextUtils#getThemeResolver
    210.      */
    211.     public static final String THEME_RESOLVER_ATTRIBUTE = DispatcherServlet.class.getName() + ".THEME_RESOLVER";
    212.     /**
    213.      * Request attribute to hold the current ThemeSource, retrievable by views.
    214.      * @see org.springframework.web.servlet.support.RequestContextUtils#getThemeSource
    215.      */
    216.     public static final String THEME_SOURCE_ATTRIBUTE = DispatcherServlet.class.getName() + ".THEME_SOURCE";
    217.     /**
    218.      * Name of request attribute that holds a read-only {@code Map<String,?>}
    219.      * with "input" flash attributes saved by a previous request, if any.
    220.      * @see org.springframework.web.servlet.support.RequestContextUtils#getInputFlashMap(HttpServletRequest)
    221.      */
    222.     public static final String INPUT_FLASH_MAP_ATTRIBUTE = DispatcherServlet.class.getName() + ".INPUT_FLASH_MAP";
    223.     /**
    224.      * Name of request attribute that holds the "output" {@link FlashMap} with
    225.      * attributes to save for a subsequent request.
    226.      * @see org.springframework.web.servlet.support.RequestContextUtils#getOutputFlashMap(HttpServletRequest)
    227.      */
    228.     public static final String OUTPUT_FLASH_MAP_ATTRIBUTE = DispatcherServlet.class.getName() + ".OUTPUT_FLASH_MAP";
    229.     /**
    230.      * Name of request attribute that holds the {@link FlashMapManager}.
    231.      * @see org.springframework.web.servlet.support.RequestContextUtils#getFlashMapManager(HttpServletRequest)
    232.      */
    233.     public static final String FLASH_MAP_MANAGER_ATTRIBUTE = DispatcherServlet.class.getName() + ".FLASH_MAP_MANAGER";
    234.     /**
    235.      * Name of request attribute that exposes an Exception resolved with a
    236.      * {@link HandlerExceptionResolver} but where no view was rendered
    237.      * (e.g. setting the status code).
    238.      */
    239.     public static final String EXCEPTION_ATTRIBUTE = DispatcherServlet.class.getName() + ".EXCEPTION";
    240.     /** Log category to use when no mapped handler is found for a request. */
    241.     public static final String PAGE_NOT_FOUND_LOG_CATEGORY = "org.springframework.web.servlet.PageNotFound";
    242.     /**
    243.      * Name of the class path resource (relative to the DispatcherServlet class)
    244.      * that defines DispatcherServlet's default strategy names.
    245.      */
    246.     private static final String DEFAULT_STRATEGIES_PATH = "DispatcherServlet.properties";
    247.     /**
    248.      * Common prefix that DispatcherServlet's default strategy attributes start with.
    249.      */
    250.     private static final String DEFAULT_STRATEGIES_PREFIX = "org.springframework.web.servlet";
    251.     /** Additional logger to use when no mapped handler is found for a request. */
    252.     protected static final Log pageNotFoundLogger = LogFactory.getLog(PAGE_NOT_FOUND_LOG_CATEGORY);
    253.     private static final Properties defaultStrategies;
    254.     static {
    255.         // Load default strategy implementations from properties file.
    256.         // This is currently strictly internal and not meant to be customized
    257.         // by application developers.
    258.         try {
    259.             ClassPathResource resource = new ClassPathResource(DEFAULT_STRATEGIES_PATH, DispatcherServlet.class);
    260.             defaultStrategies = PropertiesLoaderUtils.loadProperties(resource);
    261.         }
    262.         catch (IOException ex) {
    263.             throw new IllegalStateException("Could not load '" + DEFAULT_STRATEGIES_PATH + "': " + ex.getMessage());
    264.         }
    265.     }
    266.     /** Detect all HandlerMappings or just expect "handlerMapping" bean?. */
    267.     private boolean detectAllHandlerMappings = true;
    268.     /** Detect all HandlerAdapters or just expect "handlerAdapter" bean?. */
    269.     private boolean detectAllHandlerAdapters = true;
    270.     /** Detect all HandlerExceptionResolvers or just expect "handlerExceptionResolver" bean?. */
    271.     private boolean detectAllHandlerExceptionResolvers = true;
    272.     /** Detect all ViewResolvers or just expect "viewResolver" bean?. */
    273.     private boolean detectAllViewResolvers = true;
    274.     /** Throw a NoHandlerFoundException if no Handler was found to process this request? *.*/
    275.     private boolean throwExceptionIfNoHandlerFound = false;
    276.     /** Perform cleanup of request attributes after include request?. */
    277.     private boolean cleanupAfterInclude = true;
    278.     /** MultipartResolver used by this servlet. */
    279.     @Nullable
    280.     private MultipartResolver multipartResolver;
    281.     /** LocaleResolver used by this servlet. */
    282.     @Nullable
    283.     private LocaleResolver localeResolver;
    284.     /** ThemeResolver used by this servlet. */
    285.     @Nullable
    286.     private ThemeResolver themeResolver;
    287.     /** List of HandlerMappings used by this servlet. */
    288.     @Nullable
    289.     private List<HandlerMapping> handlerMappings;
    290.     /** List of HandlerAdapters used by this servlet. */
    291.     @Nullable
    292.     private List<HandlerAdapter> handlerAdapters;
    293.     /** List of HandlerExceptionResolvers used by this servlet. */
    294.     @Nullable
    295.     private List<HandlerExceptionResolver> handlerExceptionResolvers;
    296.     /** RequestToViewNameTranslator used by this servlet. */
    297.     @Nullable
    298.     private RequestToViewNameTranslator viewNameTranslator;
    299.     /** FlashMapManager used by this servlet. */
    300.     @Nullable
    301.     private FlashMapManager flashMapManager;
    302.     /** List of ViewResolvers used by this servlet. */
    303.     @Nullable
    304.     private List<ViewResolver> viewResolvers;
    305.     /**
    306.      * Create a new {@code DispatcherServlet} that will create its own internal web
    307.      * application context based on defaults and values provided through servlet
    308.      * init-params. Typically used in Servlet 2.5 or earlier environments, where the only
    309.      * option for servlet registration is through {@code web.xml} which requires the use
    310.      * of a no-arg constructor.
    311.      * <p>Calling {@link #setContextConfigLocation} (init-param 'contextConfigLocation')
    312.      * will dictate which XML files will be loaded by the
    313.      * {@linkplain #DEFAULT_CONTEXT_CLASS default XmlWebApplicationContext}
    314.      * <p>Calling {@link #setContextClass} (init-param 'contextClass') overrides the
    315.      * default {@code XmlWebApplicationContext} and allows for specifying an alternative class,
    316.      * such as {@code AnnotationConfigWebApplicationContext}.
    317.      * <p>Calling {@link #setContextInitializerClasses} (init-param 'contextInitializerClasses')
    318.      * indicates which {@code ApplicationContextInitializer} classes should be used to
    319.      * further configure the internal application context prior to refresh().
    320.      * @see #DispatcherServlet(WebApplicationContext)
    321.      */
    322.     public DispatcherServlet() {
    323.         super();
    324.         setDispatchOptionsRequest(true);
    325.     }
    326.     /**
    327.      * Create a new {@code DispatcherServlet} with the given web application context. This
    328.      * constructor is useful in Servlet 3.0+ environments where instance-based registration
    329.      * of servlets is possible through the {@link ServletContext#addServlet} API.
    330.      * <p>Using this constructor indicates that the following properties / init-params
    331.      * will be ignored:
    332.      * <ul>
    333.      * <li>{@link #setContextClass(Class)} / 'contextClass'</li>
    334.      * <li>{@link #setContextConfigLocation(String)} / 'contextConfigLocation'</li>
    335.      * <li>{@link #setContextAttribute(String)} / 'contextAttribute'</li>
    336.      * <li>{@link #setNamespace(String)} / 'namespace'</li>
    337.      * </ul>
    338.      * <p>The given web application context may or may not yet be {@linkplain
    339.      * ConfigurableApplicationContext#refresh() refreshed}. If it has <strong>not</strong>
    340.      * already been refreshed (the recommended approach), then the following will occur:
    341.      * <ul>
    342.      * <li>If the given context does not already have a {@linkplain
    343.      * ConfigurableApplicationContext#setParent parent}, the root application context
    344.      * will be set as the parent.</li>
    345.      * <li>If the given context has not already been assigned an {@linkplain
    346.      * ConfigurableApplicationContext#setId id}, one will be assigned to it</li>
    347.      * <li>{@code ServletContext} and {@code ServletConfig} objects will be delegated to
    348.      * the application context</li>
    349.      * <li>{@link #postProcessWebApplicationContext} will be called</li>
    350.      * <li>Any {@code ApplicationContextInitializer}s specified through the
    351.      * "contextInitializerClasses" init-param or through the {@link
    352.      * #setContextInitializers} property will be applied.</li>
    353.      * <li>{@link ConfigurableApplicationContext#refresh refresh()} will be called if the
    354.      * context implements {@link ConfigurableApplicationContext}</li>
    355.      * </ul>
    356.      * If the context has already been refreshed, none of the above will occur, under the
    357.      * assumption that the user has performed these actions (or not) per their specific
    358.      * needs.
    359.      * <p>See {@link org.springframework.web.WebApplicationInitializer} for usage examples.
    360.      * @param webApplicationContext the context to use
    361.      * @see #initWebApplicationContext
    362.      * @see #configureAndRefreshWebApplicationContext
    363.      * @see org.springframework.web.WebApplicationInitializer
    364.      */
    365.     public DispatcherServlet(WebApplicationContext webApplicationContext) {
    366.         super(webApplicationContext);
    367.         setDispatchOptionsRequest(true);
    368.     }
    369.     /**
    370.      * Set whether to detect all HandlerMapping beans in this servlet's context. Otherwise,
    371.      * just a single bean with name "handlerMapping" will be expected.
    372.      * <p>Default is "true". Turn this off if you want this servlet to use a single
    373.      * HandlerMapping, despite multiple HandlerMapping beans being defined in the context.
    374.      */
    375.     public void setDetectAllHandlerMappings(boolean detectAllHandlerMappings) {
    376.         this.detectAllHandlerMappings = detectAllHandlerMappings;
    377.     }
    378.     /**
    379.      * Set whether to detect all HandlerAdapter beans in this servlet's context. Otherwise,
    380.      * just a single bean with name "handlerAdapter" will be expected.
    381.      * <p>Default is "true". Turn this off if you want this servlet to use a single
    382.      * HandlerAdapter, despite multiple HandlerAdapter beans being defined in the context.
    383.      */
    384.     public void setDetectAllHandlerAdapters(boolean detectAllHandlerAdapters) {
    385.         this.detectAllHandlerAdapters = detectAllHandlerAdapters;
    386.     }
    387.     /**
    388.      * Set whether to detect all HandlerExceptionResolver beans in this servlet's context. Otherwise,
    389.      * just a single bean with name "handlerExceptionResolver" will be expected.
    390.      * <p>Default is "true". Turn this off if you want this servlet to use a single
    391.      * HandlerExceptionResolver, despite multiple HandlerExceptionResolver beans being defined in the context.
    392.      */
    393.     public void setDetectAllHandlerExceptionResolvers(boolean detectAllHandlerExceptionResolvers) {
    394.         this.detectAllHandlerExceptionResolvers = detectAllHandlerExceptionResolvers;
    395.     }
    396.     /**
    397.      * Set whether to detect all ViewResolver beans in this servlet's context. Otherwise,
    398.      * just a single bean with name "viewResolver" will be expected.
    399.      * <p>Default is "true". Turn this off if you want this servlet to use a single
    400.      * ViewResolver, despite multiple ViewResolver beans being defined in the context.
    401.      */
    402.     public void setDetectAllViewResolvers(boolean detectAllViewResolvers) {
    403.         this.detectAllViewResolvers = detectAllViewResolvers;
    404.     }
    405.     /**
    406.      * Set whether to throw a NoHandlerFoundException when no Handler was found for this request.
    407.      * This exception can then be caught with a HandlerExceptionResolver or an
    408.      * {@code @ExceptionHandler} controller method.
    409.      * <p>Note that if {@link org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler}
    410.      * is used, then requests will always be forwarded to the default servlet and a
    411.      * NoHandlerFoundException would never be thrown in that case.
    412.      * <p>Default is "false", meaning the DispatcherServlet sends a NOT_FOUND error through the
    413.      * Servlet response.
    414.      * @since 4.0
    415.      */
    416.     public void setThrowExceptionIfNoHandlerFound(boolean throwExceptionIfNoHandlerFound) {
    417.         this.throwExceptionIfNoHandlerFound = throwExceptionIfNoHandlerFound;
    418.     }
    419.     /**
    420.      * Set whether to perform cleanup of request attributes after an include request, that is,
    421.      * whether to reset the original state of all request attributes after the DispatcherServlet
    422.      * has processed within an include request. Otherwise, just the DispatcherServlet's own
    423.      * request attributes will be reset, but not model attributes for JSPs or special attributes
    424.      * set by views (for example, JSTL's).
    425.      * <p>Default is "true", which is strongly recommended. Views should not rely on request attributes
    426.      * having been set by (dynamic) includes. This allows JSP views rendered by an included controller
    427.      * to use any model attributes, even with the same names as in the main JSP, without causing side
    428.      * effects. Only turn this off for special needs, for example to deliberately allow main JSPs to
    429.      * access attributes from JSP views rendered by an included controller.
    430.      */
    431.     public void setCleanupAfterInclude(boolean cleanupAfterInclude) {
    432.         this.cleanupAfterInclude = cleanupAfterInclude;
    433.     }
    434.     /**
    435.      * This implementation calls {@link #initStrategies}.
    436.      */
    437.     @Override
    438.     protected void onRefresh(ApplicationContext context) {
    439.         initStrategies(context);
    440.     }
    441.     /**
    442.      * Initialize the strategy objects that this servlet uses.
    443.      * <p>May be overridden in subclasses in order to initialize further strategy objects.
    444.      */
    445.     protected void initStrategies(ApplicationContext context) {
    446.         initMultipartResolver(context);
    447.         initLocaleResolver(context);
    448.         initThemeResolver(context);
    449.         initHandlerMappings(context);
    450.         initHandlerAdapters(context);
    451.         initHandlerExceptionResolvers(context);
    452.         initRequestToViewNameTranslator(context);
    453.         initViewResolvers(context);
    454.         initFlashMapManager(context);
    455.     }
    456.     /**
    457.      * Initialize the MultipartResolver used by this class.
    458.      * <p>If no bean is defined with the given name in the BeanFactory for this namespace,
    459.      * no multipart handling is provided.
    460.      */
    461.     private void initMultipartResolver(ApplicationContext context) {
    462.         try {
    463.             this.multipartResolver = context.getBean(MULTIPART_RESOLVER_BEAN_NAME, MultipartResolver.class);
    464.             if (logger.isTraceEnabled()) {
    465.                 logger.trace("Detected " + this.multipartResolver);
    466.             }
    467.             else if (logger.isDebugEnabled()) {
    468.                 logger.debug("Detected " + this.multipartResolver.getClass().getSimpleName());
    469.             }
    470.         }
    471.         catch (NoSuchBeanDefinitionException ex) {
    472.             // Default is no multipart resolver.
    473.             this.multipartResolver = null;
    474.             if (logger.isTraceEnabled()) {
    475.                 logger.trace("No MultipartResolver '" + MULTIPART_RESOLVER_BEAN_NAME + "' declared");
    476.             }
    477.         }
    478.     }
    479.     /**
    480.      * Initialize the LocaleResolver used by this class.
    481.      * <p>If no bean is defined with the given name in the BeanFactory for this namespace,
    482.      * we default to AcceptHeaderLocaleResolver.
    483.      */
    484.     private void initLocaleResolver(ApplicationContext context) {
    485.         try {
    486.             this.localeResolver = context.getBean(LOCALE_RESOLVER_BEAN_NAME, LocaleResolver.class);
    487.             if (logger.isTraceEnabled()) {
    488.                 logger.trace("Detected " + this.localeResolver);
    489.             }
    490.             else if (logger.isDebugEnabled()) {
    491.                 logger.debug("Detected " + this.localeResolver.getClass().getSimpleName());
    492.             }
    493.         }
    494.         catch (NoSuchBeanDefinitionException ex) {
    495.             // We need to use the default.
    496.             this.localeResolver = getDefaultStrategy(context, LocaleResolver.class);
    497.             if (logger.isTraceEnabled()) {
    498.                 logger.trace("No LocaleResolver '" + LOCALE_RESOLVER_BEAN_NAME +
    499.                         "': using default [" + this.localeResolver.getClass().getSimpleName() + "]");
    500.             }
    501.         }
    502.     }
    503.     /**
    504.      * Initialize the ThemeResolver used by this class.
    505.      * <p>If no bean is defined with the given name in the BeanFactory for this namespace,
    506.      * we default to a FixedThemeResolver.
    507.      */
    508.     private void initThemeResolver(ApplicationContext context) {
    509.         try {
    510.             this.themeResolver = context.getBean(THEME_RESOLVER_BEAN_NAME, ThemeResolver.class);
    511.             if (logger.isTraceEnabled()) {
    512.                 logger.trace("Detected " + this.themeResolver);
    513.             }
    514.             else if (logger.isDebugEnabled()) {
    515.                 logger.debug("Detected " + this.themeResolver.getClass().getSimpleName());
    516.             }
    517.         }
    518.         catch (NoSuchBeanDefinitionException ex) {
    519.             // We need to use the default.
    520.             this.themeResolver = getDefaultStrategy(context, ThemeResolver.class);
    521.             if (logger.isTraceEnabled()) {
    522.                 logger.trace("No ThemeResolver '" + THEME_RESOLVER_BEAN_NAME +
    523.                         "': using default [" + this.themeResolver.getClass().getSimpleName() + "]");
    524.             }
    525.         }
    526.     }
    527.     /**
    528.      * Initialize the HandlerMappings used by this class.
    529.      * <p>If no HandlerMapping beans are defined in the BeanFactory for this namespace,
    530.      * we default to BeanNameUrlHandlerMapping.
    531.      */
    532.     private void initHandlerMappings(ApplicationContext context) {
    533.         this.handlerMappings = null;
    534.         if (this.detectAllHandlerMappings) {
    535.             // Find all HandlerMappings in the ApplicationContext, including ancestor contexts.
    536.             Map<String, HandlerMapping> matchingBeans =
    537.                     BeanFactoryUtils.beansOfTypeIncludingAncestors(context, HandlerMapping.class, true, false);
    538.             if (!matchingBeans.isEmpty()) {
    539.                 this.handlerMappings = new ArrayList<>(matchingBeans.values());
    540.                 // We keep HandlerMappings in sorted order.
    541.                 AnnotationAwareOrderComparator.sort(this.handlerMappings);
    542.             }
    543.         }
    544.         else {
    545.             try {
    546.                 HandlerMapping hm = context.getBean(HANDLER_MAPPING_BEAN_NAME, HandlerMapping.class);
    547.                 this.handlerMappings = Collections.singletonList(hm);
    548.             }
    549.             catch (NoSuchBeanDefinitionException ex) {
    550.                 // Ignore, we'll add a default HandlerMapping later.
    551.             }
    552.         }
    553.         // Ensure we have at least one HandlerMapping, by registering
    554.         // a default HandlerMapping if no other mappings are found.
    555.         if (this.handlerMappings == null) {
    556.             this.handlerMappings = getDefaultStrategies(context, HandlerMapping.class);
    557.             if (logger.isTraceEnabled()) {
    558.                 logger.trace("No HandlerMappings declared for servlet '" + getServletName() +
    559.                         "': using default strategies from DispatcherServlet.properties");
    560.             }
    561.         }
    562.     }
    563.     /**
    564.      * Initialize the HandlerAdapters used by this class.
    565.      * <p>If no HandlerAdapter beans are defined in the BeanFactory for this namespace,
    566.      * we default to SimpleControllerHandlerAdapter.
    567.      */
    568.     private void initHandlerAdapters(ApplicationContext context) {
    569.         this.handlerAdapters = null;
    570.         if (this.detectAllHandlerAdapters) {
    571.             // Find all HandlerAdapters in the ApplicationContext, including ancestor contexts.
    572.             Map<String, HandlerAdapter> matchingBeans =
    573.                     BeanFactoryUtils.beansOfTypeIncludingAncestors(context, HandlerAdapter.class, true, false);
    574.             if (!matchingBeans.isEmpty()) {
    575.                 this.handlerAdapters = new ArrayList<>(matchingBeans.values());
    576.                 // We keep HandlerAdapters in sorted order.
    577.                 AnnotationAwareOrderComparator.sort(this.handlerAdapters);
    578.             }
    579.         }
    580.         else {
    581.             try {
    582.                 HandlerAdapter ha = context.getBean(HANDLER_ADAPTER_BEAN_NAME, HandlerAdapter.class);
    583.                 this.handlerAdapters = Collections.singletonList(ha);
    584.             }
    585.             catch (NoSuchBeanDefinitionException ex) {
    586.                 // Ignore, we'll add a default HandlerAdapter later.
    587.             }
    588.         }
    589.         // Ensure we have at least some HandlerAdapters, by registering
    590.         // default HandlerAdapters if no other adapters are found.
    591.         if (this.handlerAdapters == null) {
    592.             this.handlerAdapters = getDefaultStrategies(context, HandlerAdapter.class);
    593.             if (logger.isTraceEnabled()) {
    594.                 logger.trace("No HandlerAdapters declared for servlet '" + getServletName() +
    595.                         "': using default strategies from DispatcherServlet.properties");
    596.             }
    597.         }
    598.     }
    599.     /**
    600.      * Initialize the HandlerExceptionResolver used by this class.
    601.      * <p>If no bean is defined with the given name in the BeanFactory for this namespace,
    602.      * we default to no exception resolver.
    603.      */
    604.     private void initHandlerExceptionResolvers(ApplicationContext context) {
    605.         this.handlerExceptionResolvers = null;
    606.         if (this.detectAllHandlerExceptionResolvers) {
    607.             // Find all HandlerExceptionResolvers in the ApplicationContext, including ancestor contexts.
    608.             Map<String, HandlerExceptionResolver> matchingBeans = BeanFactoryUtils
    609.                     .beansOfTypeIncludingAncestors(context, HandlerExceptionResolver.class, true, false);
    610.             if (!matchingBeans.isEmpty()) {
    611.                 this.handlerExceptionResolvers = new ArrayList<>(matchingBeans.values());
    612.                 // We keep HandlerExceptionResolvers in sorted order.
    613.                 AnnotationAwareOrderComparator.sort(this.handlerExceptionResolvers);
    614.             }
    615.         }
    616.         else {
    617.             try {
    618.                 HandlerExceptionResolver her =
    619.                         context.getBean(HANDLER_EXCEPTION_RESOLVER_BEAN_NAME, HandlerExceptionResolver.class);
    620.                 this.handlerExceptionResolvers = Collections.singletonList(her);
    621.             }
    622.             catch (NoSuchBeanDefinitionException ex) {
    623.                 // Ignore, no HandlerExceptionResolver is fine too.
    624.             }
    625.         }
    626.         // Ensure we have at least some HandlerExceptionResolvers, by registering
    627.         // default HandlerExceptionResolvers if no other resolvers are found.
    628.         if (this.handlerExceptionResolvers == null) {
    629.             this.handlerExceptionResolvers = getDefaultStrategies(context, HandlerExceptionResolver.class);
    630.             if (logger.isTraceEnabled()) {
    631.                 logger.trace("No HandlerExceptionResolvers declared in servlet '" + getServletName() +
    632.                         "': using default strategies from DispatcherServlet.properties");
    633.             }
    634.         }
    635.     }
    636.     /**
    637.      * Initialize the RequestToViewNameTranslator used by this servlet instance.
    638.      * <p>If no implementation is configured then we default to DefaultRequestToViewNameTranslator.
    639.      */
    640.     private void initRequestToViewNameTranslator(ApplicationContext context) {
    641.         try {
    642.             this.viewNameTranslator =
    643.                     context.getBean(REQUEST_TO_VIEW_NAME_TRANSLATOR_BEAN_NAME, RequestToViewNameTranslator.class);
    644.             if (logger.isTraceEnabled()) {
    645.                 logger.trace("Detected " + this.viewNameTranslator.getClass().getSimpleName());
    646.             }
    647.             else if (logger.isDebugEnabled()) {
    648.                 logger.debug("Detected " + this.viewNameTranslator);
    649.             }
    650.         }
    651.         catch (NoSuchBeanDefinitionException ex) {
    652.             // We need to use the default.
    653.             this.viewNameTranslator = getDefaultStrategy(context, RequestToViewNameTranslator.class);
    654.             if (logger.isTraceEnabled()) {
    655.                 logger.trace("No RequestToViewNameTranslator '" + REQUEST_TO_VIEW_NAME_TRANSLATOR_BEAN_NAME +
    656.                         "': using default [" + this.viewNameTranslator.getClass().getSimpleName() + "]");
    657.             }
    658.         }
    659.     }
    660.     /**
    661.      * Initialize the ViewResolvers used by this class.
    662.      * <p>If no ViewResolver beans are defined in the BeanFactory for this
    663.      * namespace, we default to InternalResourceViewResolver.
    664.      */
    665.     private void initViewResolvers(ApplicationContext context) {
    666.         this.viewResolvers = null;
    667.         if (this.detectAllViewResolvers) {
    668.             // Find all ViewResolvers in the ApplicationContext, including ancestor contexts.
    669.             Map<String, ViewResolver> matchingBeans =
    670.                     BeanFactoryUtils.beansOfTypeIncludingAncestors(context, ViewResolver.class, true, false);
    671.             if (!matchingBeans.isEmpty()) {
    672.                 this.viewResolvers = new ArrayList<>(matchingBeans.values());
    673.                 // We keep ViewResolvers in sorted order.
    674.                 AnnotationAwareOrderComparator.sort(this.viewResolvers);
    675.             }
    676.         }
    677.         else {
    678.             try {
    679.                 ViewResolver vr = context.getBean(VIEW_RESOLVER_BEAN_NAME, ViewResolver.class);
    680.                 this.viewResolvers = Collections.singletonList(vr);
    681.             }
    682.             catch (NoSuchBeanDefinitionException ex) {
    683.                 // Ignore, we'll add a default ViewResolver later.
    684.             }
    685.         }
    686.         // Ensure we have at least one ViewResolver, by registering
    687.         // a default ViewResolver if no other resolvers are found.
    688.         if (this.viewResolvers == null) {
    689.             this.viewResolvers = getDefaultStrategies(context, ViewResolver.class);
    690.             if (logger.isTraceEnabled()) {
    691.                 logger.trace("No ViewResolvers declared for servlet '" + getServletName() +
    692.                         "': using default strategies from DispatcherServlet.properties");
    693.             }
    694.         }
    695.     }
    696.     /**
    697.      * Initialize the {@link FlashMapManager} used by this servlet instance.
    698.      * <p>If no implementation is configured then we default to
    699.      * {@code org.springframework.web.servlet.support.DefaultFlashMapManager}.
    700.      */
    701.     private void initFlashMapManager(ApplicationContext context) {
    702.         try {
    703.             this.flashMapManager = context.getBean(FLASH_MAP_MANAGER_BEAN_NAME, FlashMapManager.class);
    704.             if (logger.isTraceEnabled()) {
    705.                 logger.trace("Detected " + this.flashMapManager.getClass().getSimpleName());
    706.             }
    707.             else if (logger.isDebugEnabled()) {
    708.                 logger.debug("Detected " + this.flashMapManager);
    709.             }
    710.         }
    711.         catch (NoSuchBeanDefinitionException ex) {
    712.             // We need to use the default.
    713.             this.flashMapManager = getDefaultStrategy(context, FlashMapManager.class);
    714.             if (logger.isTraceEnabled()) {
    715.                 logger.trace("No FlashMapManager '" + FLASH_MAP_MANAGER_BEAN_NAME +
    716.                         "': using default [" + this.flashMapManager.getClass().getSimpleName() + "]");
    717.             }
    718.         }
    719.     }
    720.     /**
    721.      * Return this servlet's ThemeSource, if any; else return {@code null}.
    722.      * <p>Default is to return the WebApplicationContext as ThemeSource,
    723.      * provided that it implements the ThemeSource interface.
    724.      * @return the ThemeSource, if any
    725.      * @see #getWebApplicationContext()
    726.      */
    727.     @Nullable
    728.     public final ThemeSource getThemeSource() {
    729.         return (getWebApplicationContext() instanceof ThemeSource ? (ThemeSource) getWebApplicationContext() : null);
    730.     }
    731.     /**
    732.      * Obtain this servlet's MultipartResolver, if any.
    733.      * @return the MultipartResolver used by this servlet, or {@code null} if none
    734.      * (indicating that no multipart support is available)
    735.      */
    736.     @Nullable
    737.     public final MultipartResolver getMultipartResolver() {
    738.         return this.multipartResolver;
    739.     }
    740.     /**
    741.      * Return the configured {@link HandlerMapping} beans that were detected by
    742.      * type in the {@link WebApplicationContext} or initialized based on the
    743.      * default set of strategies from {@literal DispatcherServlet.properties}.
    744.      * <p><strong>Note:</strong> This method may return {@code null} if invoked
    745.      * prior to {@link #onRefresh(ApplicationContext)}.
    746.      * @return an immutable list with the configured mappings, or {@code null}
    747.      * if not initialized yet
    748.      * @since 5.0
    749.      */
    750.     @Nullable
    751.     public final List<HandlerMapping> getHandlerMappings() {
    752.         return (this.handlerMappings != null ? Collections.unmodifiableList(this.handlerMappings) : null);
    753.     }
    754.     /**
    755.      * Return the default strategy object for the given strategy interface.
    756.      * <p>The default implementation delegates to {@link #getDefaultStrategies},
    757.      * expecting a single object in the list.
    758.      * @param context the current WebApplicationContext
    759.      * @param strategyInterface the strategy interface
    760.      * @return the corresponding strategy object
    761.      * @see #getDefaultStrategies
    762.      */
    763.     protected <T> T getDefaultStrategy(ApplicationContext context, Class<T> strategyInterface) {
    764.         List<T> strategies = getDefaultStrategies(context, strategyInterface);
    765.         if (strategies.size() != 1) {
    766.             throw new BeanInitializationException(
    767.                     "DispatcherServlet needs exactly 1 strategy for interface [" + strategyInterface.getName() + "]");
    768.         }
    769.         return strategies.get(0);
    770.     }
    771.     /**
    772.      * Create a List of default strategy objects for the given strategy interface.
    773.      * <p>The default implementation uses the "DispatcherServlet.properties" file (in the same
    774.      * package as the DispatcherServlet class) to determine the class names. It instantiates
    775.      * the strategy objects through the context's BeanFactory.
    776.      * @param context the current WebApplicationContext
    777.      * @param strategyInterface the strategy interface
    778.      * @return the List of corresponding strategy objects
    779.      */
    780.     @SuppressWarnings("unchecked")
    781.     protected <T> List<T> getDefaultStrategies(ApplicationContext context, Class<T> strategyInterface) {
    782.         String key = strategyInterface.getName();
    783.         String value = defaultStrategies.getProperty(key);
    784.         if (value != null) {
    785.             String[] classNames = StringUtils.commaDelimitedListToStringArray(value);
    786.             List<T> strategies = new ArrayList<>(classNames.length);
    787.             for (String className : classNames) {
    788.                 try {
    789.                     Class<?> clazz = ClassUtils.forName(className, DispatcherServlet.class.getClassLoader());
    790.                     Object strategy = createDefaultStrategy(context, clazz);
    791.                     strategies.add((T) strategy);
    792.                 }
    793.                 catch (ClassNotFoundException ex) {
    794.                     throw new BeanInitializationException(
    795.                             "Could not find DispatcherServlet's default strategy class [" + className +
    796.                             "] for interface [" + key + "]", ex);
    797.                 }
    798.                 catch (LinkageError err) {
    799.                     throw new BeanInitializationException(
    800.                             "Unresolvable class definition for DispatcherServlet's default strategy class [" +
    801.                             className + "] for interface [" + key + "]", err);
    802.                 }
    803.             }
    804.             return strategies;
    805.         }
    806.         else {
    807.             return new LinkedList<>();
    808.         }
    809.     }
    810.     /**
    811.      * Create a default strategy.
    812.      * <p>The default implementation uses
    813.      * {@link org.springframework.beans.factory.config.AutowireCapableBeanFactory#createBean}.
    814.      * @param context the current WebApplicationContext
    815.      * @param clazz the strategy implementation class to instantiate
    816.      * @return the fully configured strategy instance
    817.      * @see org.springframework.context.ApplicationContext#getAutowireCapableBeanFactory()
    818.      * @see org.springframework.beans.factory.config.AutowireCapableBeanFactory#createBean
    819.      */
    820.     protected Object createDefaultStrategy(ApplicationContext context, Class<?> clazz) {
    821.         return context.getAutowireCapableBeanFactory().createBean(clazz);
    822.     }
    823.     /**
    824.      * Exposes the DispatcherServlet-specific request attributes and delegates to {@link #doDispatch}
    825.      * for the actual dispatching.
    826.      */
    827.     @Override
    828.     protected void doService(HttpServletRequest request, HttpServletResponse response) throws Exception {
    829.         logRequest(request);
    830.         // Keep a snapshot of the request attributes in case of an include,
    831.         // to be able to restore the original attributes after the include.
    832.         Map<String, Object> attributesSnapshot = null;
    833.         if (WebUtils.isIncludeRequest(request)) {
    834.             attributesSnapshot = new HashMap<>();
    835.             Enumeration<?> attrNames = request.getAttributeNames();
    836.             while (attrNames.hasMoreElements()) {
    837.                 String attrName = (String) attrNames.nextElement();
    838.                 if (this.cleanupAfterInclude || attrName.startsWith(DEFAULT_STRATEGIES_PREFIX)) {
    839.                     attributesSnapshot.put(attrName, request.getAttribute(attrName));
    840.                 }
    841.             }
    842.         }
    843.         // Make framework objects available to handlers and view objects.
    844.         request.setAttribute(WEB_APPLICATION_CONTEXT_ATTRIBUTE, getWebApplicationContext());
    845.         request.setAttribute(LOCALE_RESOLVER_ATTRIBUTE, this.localeResolver);
    846.         request.setAttribute(THEME_RESOLVER_ATTRIBUTE, this.themeResolver);
    847.         request.setAttribute(THEME_SOURCE_ATTRIBUTE, getThemeSource());
    848.         if (this.flashMapManager != null) {
    849.             FlashMap inputFlashMap = this.flashMapManager.retrieveAndUpdate(request, response);
    850.             if (inputFlashMap != null) {
    851.                 request.setAttribute(INPUT_FLASH_MAP_ATTRIBUTE, Collections.unmodifiableMap(inputFlashMap));
    852.             }
    853.             request.setAttribute(OUTPUT_FLASH_MAP_ATTRIBUTE, new FlashMap());
    854.             request.setAttribute(FLASH_MAP_MANAGER_ATTRIBUTE, this.flashMapManager);
    855.         }
    856.         try {
    857.             doDispatch(request, response);
    858.         }
    859.         finally {
    860.             if (!WebAsyncUtils.getAsyncManager(request).isConcurrentHandlingStarted()) {
    861.                 // Restore the original attribute snapshot, in case of an include.
    862.                 if (attributesSnapshot != null) {
    863.                     restoreAttributesAfterInclude(request, attributesSnapshot);
    864.                 }
    865.             }
    866.         }
    867.     }
    868.     private void logRequest(HttpServletRequest request) {
    869.         LogFormatUtils.traceDebug(logger, traceOn -> {
    870.             String params;
    871.             if (isEnableLoggingRequestDetails()) {
    872.                 params = request.getParameterMap().entrySet().stream()
    873.                         .map(entry -> entry.getKey() + ":" + Arrays.toString(entry.getValue()))
    874.                         .collect(Collectors.joining(", "));
    875.             }
    876.             else {
    877.                 params = (request.getParameterMap().isEmpty() ? "" : "masked");
    878.             }
    879.             String queryString = request.getQueryString();
    880.             String queryClause = (StringUtils.hasLength(queryString) ? "?" + queryString : "");
    881.             String dispatchType = (!request.getDispatcherType().equals(DispatcherType.REQUEST) ?
    882.                     """ + request.getDispatcherType().name() + "" dispatch for " : "");
    883.             String message = (dispatchType + request.getMethod() + " "" + getRequestUri(request) +
    884.                     queryClause + "", parameters={" + params + "}");
    885.             if (traceOn) {
    886.                 List<String> values = Collections.list(request.getHeaderNames());
    887.                 String headers = values.size() > 0 ? "masked" : "";
    888.                 if (isEnableLoggingRequestDetails()) {
    889.                     headers = values.stream().map(name -> name + ":" + Collections.list(request.getHeaders(name)))
    890.                             .collect(Collectors.joining(", "));
    891.                 }
    892.                 return message + ", headers={" + headers + "} in DispatcherServlet '" + getServletName() + "'";
    893.             }
    894.             else {
    895.                 return message;
    896.             }
    897.         });
    898.     }
    899.     /**
    900.      * Process the actual dispatching to the handler.
    901.      * <p>The handler will be obtained by applying the servlet's HandlerMappings in order.
    902.      * The HandlerAdapter will be obtained by querying the servlet's installed HandlerAdapters
    903.      * to find the first that supports the handler class.
    904.      * <p>All HTTP methods are handled by this method. It's up to HandlerAdapters or handlers
    905.      * themselves to decide which methods are acceptable.
    906.      * @param request current HTTP request
    907.      * @param response current HTTP response
    908.      * @throws Exception in case of any kind of processing failure
    909.      */
    910.     protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
    911.         HttpServletRequest processedRequest = request;
    912.         HandlerExecutionChain mappedHandler = null;
    913.         boolean multipartRequestParsed = false;
    914.         WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
    915.         try {
    916.             ModelAndView mv = null;
    917.             Exception dispatchException = null;
    918.             try {
    919.                 processedRequest = checkMultipart(request);
    920.                 multipartRequestParsed = (processedRequest != request);
    921.                 // Determine handler for the current request.
    922.                 mappedHandler = getHandler(processedRequest);
    923.                 if (mappedHandler == null) {
    924.                     noHandlerFound(processedRequest, response);
    925.                     return;
    926.                 }
    927.                 // Determine handler adapter for the current request.
    928.                 HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());
    929.                 // Process last-modified header, if supported by the handler.
    930.                 String method = request.getMethod();
    931.                 boolean isGet = "GET".equals(method);
    932.                 if (isGet || "HEAD".equals(method)) {
    933.                     long lastModified = ha.getLastModified(request, mappedHandler.getHandler());
    934.                     if (new ServletWebRequest(request, response).checkNotModified(lastModified) && isGet) {
    935.                         return;
    936.                     }
    937.                 }
    938.                 if (!mappedHandler.applyPreHandle(processedRequest, response)) {
    939.                     return;
    940.                 }
    941.                 // Actually invoke the handler.
    942.                 mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
    943.                 if (asyncManager.isConcurrentHandlingStarted()) {
    944.                     return;
    945.                 }
    946.                 applyDefaultViewName(processedRequest, mv);
    947.                 mappedHandler.applyPostHandle(processedRequest, response, mv);
    948.             }
    949.             catch (Exception ex) {
    950.                 dispatchException = ex;
    951.             }
    952.             catch (Throwable err) {
    953.                 // As of 4.3, we're processing Errors thrown from handler methods as well,
    954.                 // making them available for @ExceptionHandler methods and other scenarios.
    955.                 dispatchException = new NestedServletException("Handler dispatch failed", err);
    956.             }
    957.             processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);
    958.         }
    959.         catch (Exception ex) {
    960.             triggerAfterCompletion(processedRequest, response, mappedHandler, ex);
    961.         }
    962.         catch (Throwable err) {
    963.             triggerAfterCompletion(processedRequest, response, mappedHandler,
    964.                     new NestedServletException("Handler processing failed", err));
    965.         }
    966.         finally {
    967.             if (asyncManager.isConcurrentHandlingStarted()) {
    968.                 // Instead of postHandle and afterCompletion
    969.                 if (mappedHandler != null) {
    970.                     mappedHandler.applyAfterConcurrentHandlingStarted(processedRequest, response);
    971.                 }
    972.             }
    973.             else {
    974.                 // Clean up any resources used by a multipart request.
    975.                 if (multipartRequestParsed) {
    976.                     cleanupMultipart(processedRequest);
    977.                 }
    978.             }
    979.         }
    980.     }
    981.     /**
    982.      * Do we need view name translation?
    983.      */
    984.     private void applyDefaultViewName(HttpServletRequest request, @Nullable ModelAndView mv) throws Exception {
    985.         if (mv != null && !mv.hasView()) {
    986.             String defaultViewName = getDefaultViewName(request);
    987.             if (defaultViewName != null) {
    988.                 mv.setViewName(defaultViewName);
    989.             }
    990.         }
    991.     }
    992.     /**
    993.      * Handle the result of handler selection and handler invocation, which is
    994.      * either a ModelAndView or an Exception to be resolved to a ModelAndView.
    995.      */
    996.     private void processDispatchResult(HttpServletRequest request, HttpServletResponse response,
    997.             @Nullable HandlerExecutionChain mappedHandler, @Nullable ModelAndView mv,
    998.             @Nullable Exception exception) throws Exception {
    999.         boolean errorView = false;
    1000.         if (exception != null) {
    1001.             if (exception instanceof ModelAndViewDefiningException) {
    1002.                 logger.debug("ModelAndViewDefiningException encountered", exception);
    1003.                 mv = ((ModelAndViewDefiningException) exception).getModelAndView();
    1004.             }
    1005.             else {
    1006.                 Object handler = (mappedHandler != null ? mappedHandler.getHandler() : null);
    1007.                 mv = processHandlerException(request, response, handler, exception);
    1008.                 errorView = (mv != null);
    1009.             }
    1010.         }
    1011.         // Did the handler return a view to render?
    1012.         if (mv != null && !mv.wasCleared()) {
    1013.             render(mv, request, response);
    1014.             if (errorView) {
    1015.                 WebUtils.clearErrorRequestAttributes(request);
    1016.             }
    1017.         }
    1018.         else {
    1019.             if (logger.isTraceEnabled()) {
    1020.                 logger.trace("No view rendering, null ModelAndView returned.");
    1021.             }
    1022.         }
    1023.         if (WebAsyncUtils.getAsyncManager(request).isConcurrentHandlingStarted()) {
    1024.             // Concurrent handling started during a forward
    1025.             return;
    1026.         }
    1027.         if (mappedHandler != null) {
    1028.             // Exception (if any) is already handled..
    1029.             mappedHandler.triggerAfterCompletion(request, response, null);
    1030.         }
    1031.     }
    1032.     /**
    1033.      * Build a LocaleContext for the given request, exposing the request's primary locale as current locale.
    1034.      * <p>The default implementation uses the dispatcher's LocaleResolver to obtain the current locale,
    1035.      * which might change during a request.
    1036.      * @param request current HTTP request
    1037.      * @return the corresponding LocaleContext
    1038.      */
    1039.     @Override
    1040.     protected LocaleContext buildLocaleContext(final HttpServletRequest request) {
    1041.         LocaleResolver lr = this.localeResolver;
    1042.         if (lr instanceof LocaleContextResolver) {
    1043.             return ((LocaleContextResolver) lr).resolveLocaleContext(request);
    1044.         }
    1045.         else {
    1046.             return () -> (lr != null ? lr.resolveLocale(request) : request.getLocale());
    1047.         }
    1048.     }
    1049.     /**
    1050.      * Convert the request into a multipart request, and make multipart resolver available.
    1051.      * <p>If no multipart resolver is set, simply use the existing request.
    1052.      * @param request current HTTP request
    1053.      * @return the processed request (multipart wrapper if necessary)
    1054.      * @see MultipartResolver#resolveMultipart
    1055.      */
    1056.     protected HttpServletRequest checkMultipart(HttpServletRequest request) throws MultipartException {
    1057.         if (this.multipartResolver != null && this.multipartResolver.isMultipart(request)) {
    1058.             if (WebUtils.getNativeRequest(request, MultipartHttpServletRequest.class) != null) {
    1059.                 if (request.getDispatcherType().equals(DispatcherType.REQUEST)) {
    1060.                     logger.trace("Request already resolved to MultipartHttpServletRequest, e.g. by MultipartFilter");
    1061.                 }
    1062.             }
    1063.             else if (hasMultipartException(request)) {
    1064.                 logger.debug("Multipart resolution previously failed for current request - " +
    1065.                         "skipping re-resolution for undisturbed error rendering");
    1066.             }
    1067.             else {
    1068.                 try {
    1069.                     return this.multipartResolver.resolveMultipart(request);
    1070.                 }
    1071.                 catch (MultipartException ex) {
    1072.                     if (request.getAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE) != null) {
    1073.                         logger.debug("Multipart resolution failed for error dispatch", ex);
    1074.                         // Keep processing error dispatch with regular request handle below
    1075.                     }
    1076.                     else {
    1077.                         throw ex;
    1078.                     }
    1079.                 }
    1080.             }
    1081.         }
    1082.         // If not returned before: return original request.
    1083.         return request;
    1084.     }
    1085.     /**
    1086.      * Check "javax.servlet.error.exception" attribute for a multipart exception.
    1087.      */
    1088.     private boolean hasMultipartException(HttpServletRequest request) {
    1089.         Throwable error = (Throwable) request.getAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE);
    1090.         while (error != null) {
    1091.             if (error instanceof MultipartException) {
    1092.                 return true;
    1093.             }
    1094.             error = error.getCause();
    1095.         }
    1096.         return false;
    1097.     }
    1098.     /**
    1099.      * Clean up any resources used by the given multipart request (if any).
    1100.      * @param request current HTTP request
    1101.      * @see MultipartResolver#cleanupMultipart
    1102.      */
    1103.     protected void cleanupMultipart(HttpServletRequest request) {
    1104.         if (this.multipartResolver != null) {
    1105.             MultipartHttpServletRequest multipartRequest =
    1106.                     WebUtils.getNativeRequest(request, MultipartHttpServletRequest.class);
    1107.             if (multipartRequest != null) {
    1108.                 this.multipartResolver.cleanupMultipart(multipartRequest);
    1109.             }
    1110.         }
    1111.     }
    1112.     /**
    1113.      * Return the HandlerExecutionChain for this request.
    1114.      * <p>Tries all handler mappings in order.
    1115.      * @param request current HTTP request
    1116.      * @return the HandlerExecutionChain, or {@code null} if no handler could be found
    1117.      */
    1118.     @Nullable
    1119.     protected HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
    1120.         if (this.handlerMappings != null) {
    1121.             for (HandlerMapping mapping : this.handlerMappings) {
    1122.                 HandlerExecutionChain handler = mapping.getHandler(request);
    1123.                 if (handler != null) {
    1124.                     return handler;
    1125.                 }
    1126.             }
    1127.         }
    1128.         return null;
    1129.     }
    1130.     /**
    1131.      * No handler found -> set appropriate HTTP response status.
    1132.      * @param request current HTTP request
    1133.      * @param response current HTTP response
    1134.      * @throws Exception if preparing the response failed
    1135.      */
    1136.     protected void noHandlerFound(HttpServletRequest request, HttpServletResponse response) throws Exception {
    1137.         if (pageNotFoundLogger.isWarnEnabled()) {
    1138.             pageNotFoundLogger.warn("No mapping for " + request.getMethod() + " " + getRequestUri(request));
    1139.         }
    1140.         if (this.throwExceptionIfNoHandlerFound) {
    1141.             throw new NoHandlerFoundException(request.getMethod(), getRequestUri(request),
    1142.                     new ServletServerHttpRequest(request).getHeaders());
    1143.         }
    1144.         else {
    1145.             response.sendError(HttpServletResponse.SC_NOT_FOUND);
    1146.         }
    1147.     }
    1148.     /**
    1149.      * Return the HandlerAdapter for this handler object.
    1150.      * @param handler the handler object to find an adapter for
    1151.      * @throws ServletException if no HandlerAdapter can be found for the handler. This is a fatal error.
    1152.      */
    1153.     protected HandlerAdapter getHandlerAdapter(Object handler) throws ServletException {
    1154.         if (this.handlerAdapters != null) {
    1155.             for (HandlerAdapter adapter : this.handlerAdapters) {
    1156.                 if (adapter.supports(handler)) {
    1157.                     return adapter;
    1158.                 }
    1159.             }
    1160.         }
    1161.         throw new ServletException("No adapter for handler [" + handler +
    1162.                 "]: The DispatcherServlet configuration needs to include a HandlerAdapter that supports this handler");
    1163.     }
    1164.     /**
    1165.      * Determine an error ModelAndView via the registered HandlerExceptionResolvers.
    1166.      * @param request current HTTP request
    1167.      * @param response current HTTP response
    1168.      * @param handler the executed handler, or {@code null} if none chosen at the time of the exception
    1169.      * (for example, if multipart resolution failed)
    1170.      * @param ex the exception that got thrown during handler execution
    1171.      * @return a corresponding ModelAndView to forward to
    1172.      * @throws Exception if no error ModelAndView found
    1173.      */
    1174.     @Nullable
    1175.     protected ModelAndView processHandlerException(HttpServletRequest request, HttpServletResponse response,
    1176.             @Nullable Object handler, Exception ex) throws Exception {
    1177.         // Success and error responses may use different content types
    1178.         request.removeAttribute(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE);
    1179.         // Check registered HandlerExceptionResolvers...
    1180.         ModelAndView exMv = null;
    1181.         if (this.handlerExceptionResolvers != null) {
    1182.             for (HandlerExceptionResolver resolver : this.handlerExceptionResolvers) {
    1183.                 exMv = resolver.resolveException(request, response, handler, ex);
    1184.                 if (exMv != null) {
    1185.                     break;
    1186.                 }
    1187.             }
    1188.         }
    1189.         if (exMv != null) {
    1190.             if (exMv.isEmpty()) {
    1191.                 request.setAttribute(EXCEPTION_ATTRIBUTE, ex);
    1192.                 return null;
    1193.             }
    1194.             // We might still need view name translation for a plain error model...
    1195.             if (!exMv.hasView()) {
    1196.                 String defaultViewName = getDefaultViewName(request);
    1197.                 if (defaultViewName != null) {
    1198.                     exMv.setViewName(defaultViewName);
    1199.                 }
    1200.             }
    1201.             if (logger.isTraceEnabled()) {
    1202.                 logger.trace("Using resolved error view: " + exMv, ex);
    1203.             }
    1204.             else if (logger.isDebugEnabled()) {
    1205.                 logger.debug("Using resolved error view: " + exMv);
    1206.             }
    1207.             WebUtils.exposeErrorRequestAttributes(request, ex, getServletName());
    1208.             return exMv;
    1209.         }
    1210.         throw ex;
    1211.     }
    1212.     /**
    1213.      * Render the given ModelAndView.
    1214.      * <p>This is the last stage in handling a request. It may involve resolving the view by name.
    1215.      * @param mv the ModelAndView to render
    1216.      * @param request current HTTP servlet request
    1217.      * @param response current HTTP servlet response
    1218.      * @throws ServletException if view is missing or cannot be resolved
    1219.      * @throws Exception if there's a problem rendering the view
    1220.      */
    1221.     protected void render(ModelAndView mv, HttpServletRequest request, HttpServletResponse response) throws Exception {
    1222.         // Determine locale for request and apply it to the response.
    1223.         Locale locale =
    1224.                 (this.localeResolver != null ? this.localeResolver.resolveLocale(request) : request.getLocale());
    1225.         response.setLocale(locale);
    1226.         View view;
    1227.         String viewName = mv.getViewName();
    1228.         if (viewName != null) {
    1229.             // We need to resolve the view name.
    1230.             view = resolveViewName(viewName, mv.getModelInternal(), locale, request);
    1231.             if (view == null) {
    1232.                 throw new ServletException("Could not resolve view with name '" + mv.getViewName() +
    1233.                         "' in servlet with name '" + getServletName() + "'");
    1234.             }
    1235.         }
    1236.         else {
    1237.             // No need to lookup: the ModelAndView object contains the actual View object.
    1238.             view = mv.getView();
    1239.             if (view == null) {
    1240.                 throw new ServletException("ModelAndView [" + mv + "] neither contains a view name nor a " +
    1241.                         "View object in servlet with name '" + getServletName() + "'");
    1242.             }
    1243.         }
    1244.         // Delegate to the View object for rendering.
    1245.         if (logger.isTraceEnabled()) {
    1246.             logger.trace("Rendering view [" + view + "] ");
    1247.         }
    1248.         try {
    1249.             if (mv.getStatus() != null) {
    1250.                 response.setStatus(mv.getStatus().value());
    1251.             }
    1252.             view.render(mv.getModelInternal(), request, response);
    1253.         }
    1254.         catch (Exception ex) {
    1255.             if (logger.isDebugEnabled()) {
    1256.                 logger.debug("Error rendering view [" + view + "]", ex);
    1257.             }
    1258.             throw ex;
    1259.         }
    1260.     }
    1261.     /**
    1262.      * Translate the supplied request into a default view name.
    1263.      * @param request current HTTP servlet request
    1264.      * @return the view name (or {@code null} if no default found)
    1265.      * @throws Exception if view name translation failed
    1266.      */
    1267.     @Nullable
    1268.     protected String getDefaultViewName(HttpServletRequest request) throws Exception {
    1269.         return (this.viewNameTranslator != null ? this.viewNameTranslator.getViewName(request) : null);
    1270.     }
    1271.     /**
    1272.      * Resolve the given view name into a View object (to be rendered).
    1273.      * <p>The default implementations asks all ViewResolvers of this dispatcher.
    1274.      * Can be overridden for custom resolution strategies, potentially based on
    1275.      * specific model attributes or request parameters.
    1276.      * @param viewName the name of the view to resolve
    1277.      * @param model the model to be passed to the view
    1278.      * @param locale the current locale
    1279.      * @param request current HTTP servlet request
    1280.      * @return the View object, or {@code null} if none found
    1281.      * @throws Exception if the view cannot be resolved
    1282.      * (typically in case of problems creating an actual View object)
    1283.      * @see ViewResolver#resolveViewName
    1284.      */
    1285.     @Nullable
    1286.     protected View resolveViewName(String viewName, @Nullable Map<String, Object> model,
    1287.             Locale locale, HttpServletRequest request) throws Exception {
    1288.         if (this.viewResolvers != null) {
    1289.             for (ViewResolver viewResolver : this.viewResolvers) {
    1290.                 View view = viewResolver.resolveViewName(viewName, locale);
    1291.                 if (view != null) {
    1292.                     return view;
    1293.                 }
    1294.             }
    1295.         }
    1296.         return null;
    1297.     }
    1298.     private void triggerAfterCompletion(HttpServletRequest request, HttpServletResponse response,
    1299.             @Nullable HandlerExecutionChain mappedHandler, Exception ex) throws Exception {
    1300.         if (mappedHandler != null) {
    1301.             mappedHandler.triggerAfterCompletion(request, response, ex);
    1302.         }
    1303.         throw ex;
    1304.     }
    1305.     /**
    1306.      * Restore the request attributes after an include.
    1307.      * @param request current HTTP request
    1308.      * @param attributesSnapshot the snapshot of the request attributes before the include
    1309.      */
    1310.     @SuppressWarnings("unchecked")
    1311.     private void restoreAttributesAfterInclude(HttpServletRequest request, Map<?, ?> attributesSnapshot) {
    1312.         // Need to copy into separate Collection here, to avoid side effects
    1313.         // on the Enumeration when removing attributes.
    1314.         Set<String> attrsToCheck = new HashSet<>();
    1315.         Enumeration<?> attrNames = request.getAttributeNames();
    1316.         while (attrNames.hasMoreElements()) {
    1317.             String attrName = (String) attrNames.nextElement();
    1318.             if (this.cleanupAfterInclude || attrName.startsWith(DEFAULT_STRATEGIES_PREFIX)) {
    1319.                 attrsToCheck.add(attrName);
    1320.             }
    1321.         }
    1322.         // Add attributes that may have been removed
    1323.         attrsToCheck.addAll((Set<String>) attributesSnapshot.keySet());
    1324.         // Iterate over the attributes to check, restoring the original value
    1325.         // or removing the attribute, respectively, if appropriate.
    1326.         for (String attrName : attrsToCheck) {
    1327.             Object attrValue = attributesSnapshot.get(attrName);
    1328.             if (attrValue == null) {
    1329.                 request.removeAttribute(attrName);
    1330.             }
    1331.             else if (attrValue != request.getAttribute(attrName)) {
    1332.                 request.setAttribute(attrName, attrValue);
    1333.             }
    1334.         }
    1335.     }
    1336.     private static String getRequestUri(HttpServletRequest request) {
    1337.         String uri = (String) request.getAttribute(WebUtils.INCLUDE_REQUEST_URI_ATTRIBUTE);
    1338.         if (uri == null) {
    1339.             uri = request.getRequestURI();
    1340.         }
    1341.         return uri;
    1342.     }
    1343. }
    复制代码
    DispatcherServlet@Controller表明这是一个控制器,然后@RequestMapping代表请求路径和控制器(或其方法)的映射关系,它会在Web服务器启动Spring MVC时,就被扫描到HandlerMapping的机制中存储,之后在用户发起请求被DispatcherServlet拦截后,通过URI和其他的条件,通过HandlerMapper机制就能找到对应的控制器(或其方法)进行响应。只是通过HandlerMapping返回的是一个HandlerExecutionChain对象
    1. /*
    2. * Copyright 2002-2020 the original author or authors.
    3. *
    4. * Licensed under the Apache License, Version 2.0 (the "License");
    5. * you may not use this file except in compliance with the License.
    6. * You may obtain a copy of the License at
    7. *
    8. *      https://www.apache.org/licenses/LICENSE-2.0
    9. *
    10. * Unless required by applicable law or agreed to in writing, software
    11. * distributed under the License is distributed on an "AS IS" BASIS,
    12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13. * See the License for the specific language governing permissions and
    14. * limitations under the License.
    15. */
    16. package org.springframework.web.servlet;
    17. import java.util.ArrayList;
    18. import java.util.List;
    19. import javax.servlet.http.HttpServletRequest;
    20. import javax.servlet.http.HttpServletResponse;
    21. import org.apache.commons.logging.Log;
    22. import org.apache.commons.logging.LogFactory;
    23. import org.springframework.lang.Nullable;
    24. import org.springframework.util.CollectionUtils;
    25. import org.springframework.util.ObjectUtils;
    26. /**
    27. * Handler execution chain, consisting of handler object and any handler interceptors.
    28. * Returned by HandlerMapping's {@link HandlerMapping#getHandler} method.
    29. *
    30. * @author Juergen Hoeller
    31. * @since 20.06.2003
    32. * @see HandlerInterceptor
    33. */
    34. public class HandlerExecutionChain {
    35.     private static final Log logger = LogFactory.getLog(HandlerExecutionChain.class);
    36.     private final Object handler;
    37.     @Nullable
    38.     private HandlerInterceptor[] interceptors;
    39.     @Nullable
    40.     private List<HandlerInterceptor> interceptorList;
    41.     private int interceptorIndex = -1;
    42.     /**
    43.      * Create a new HandlerExecutionChain.
    44.      * @param handler the handler object to execute
    45.      */
    46.     public HandlerExecutionChain(Object handler) {
    47.         this(handler, (HandlerInterceptor[]) null);
    48.     }
    49.     /**
    50.      * Create a new HandlerExecutionChain.
    51.      * @param handler the handler object to execute
    52.      * @param interceptors the array of interceptors to apply
    53.      * (in the given order) before the handler itself executes
    54.      */
    55.     public HandlerExecutionChain(Object handler, @Nullable HandlerInterceptor... interceptors) {
    56.         if (handler instanceof HandlerExecutionChain) {
    57.             HandlerExecutionChain originalChain = (HandlerExecutionChain) handler;
    58.             this.handler = originalChain.getHandler();
    59.             this.interceptorList = new ArrayList<>();
    60.             CollectionUtils.mergeArrayIntoCollection(originalChain.getInterceptors(), this.interceptorList);
    61.             CollectionUtils.mergeArrayIntoCollection(interceptors, this.interceptorList);
    62.         }
    63.         else {
    64.             this.handler = handler;
    65.             this.interceptors = interceptors;
    66.         }
    67.     }
    68.     /**
    69.      * Return the handler object to execute.
    70.      */
    71.     public Object getHandler() {
    72.         return this.handler;
    73.     }
    74.     /**
    75.      * Add the given interceptor to the end of this chain.
    76.      */
    77.     public void addInterceptor(HandlerInterceptor interceptor) {
    78.         initInterceptorList().add(interceptor);
    79.     }
    80.     /**
    81.      * Add the given interceptor at the specified index of this chain.
    82.      * @since 5.2
    83.      */
    84.     public void addInterceptor(int index, HandlerInterceptor interceptor) {
    85.         initInterceptorList().add(index, interceptor);
    86.     }
    87.     /**
    88.      * Add the given interceptors to the end of this chain.
    89.      */
    90.     public void addInterceptors(HandlerInterceptor... interceptors) {
    91.         if (!ObjectUtils.isEmpty(interceptors)) {
    92.             CollectionUtils.mergeArrayIntoCollection(interceptors, initInterceptorList());
    93.         }
    94.     }
    95.     private List<HandlerInterceptor> initInterceptorList() {
    96.         if (this.interceptorList == null) {
    97.             this.interceptorList = new ArrayList<>();
    98.             if (this.interceptors != null) {
    99.                 // An interceptor array specified through the constructor
    100.                 CollectionUtils.mergeArrayIntoCollection(this.interceptors, this.interceptorList);
    101.             }
    102.         }
    103.         this.interceptors = null;
    104.         return this.interceptorList;
    105.     }
    106.     /**
    107.      * Return the array of interceptors to apply (in the given order).
    108.      * @return the array of HandlerInterceptors instances (may be {@code null})
    109.      */
    110.     @Nullable
    111.     public HandlerInterceptor[] getInterceptors() {
    112.         if (this.interceptors == null && this.interceptorList != null) {
    113.             this.interceptors = this.interceptorList.toArray(new HandlerInterceptor[0]);
    114.         }
    115.         return this.interceptors;
    116.     }
    117.     /**
    118.      * Apply preHandle methods of registered interceptors.
    119.      * @return {@code true} if the execution chain should proceed with the
    120.      * next interceptor or the handler itself. Else, DispatcherServlet assumes
    121.      * that this interceptor has already dealt with the response itself.
    122.      */
    123.     boolean applyPreHandle(HttpServletRequest request, HttpServletResponse response) throws Exception {
    124.         HandlerInterceptor[] interceptors = getInterceptors();
    125.         if (!ObjectUtils.isEmpty(interceptors)) {
    126.             for (int i = 0; i < interceptors.length; i++) {
    127.                 HandlerInterceptor interceptor = interceptors[i];
    128.                 if (!interceptor.preHandle(request, response, this.handler)) {
    129.                     triggerAfterCompletion(request, response, null);
    130.                     return false;
    131.                 }
    132.                 this.interceptorIndex = i;
    133.             }
    134.         }
    135.         return true;
    136.     }
    137.     /**
    138.      * Apply postHandle methods of registered interceptors.
    139.      */
    140.     void applyPostHandle(HttpServletRequest request, HttpServletResponse response, @Nullable ModelAndView mv)
    141.             throws Exception {
    142.         HandlerInterceptor[] interceptors = getInterceptors();
    143.         if (!ObjectUtils.isEmpty(interceptors)) {
    144.             for (int i = interceptors.length - 1; i >= 0; i--) {
    145.                 HandlerInterceptor interceptor = interceptors[i];
    146.                 interceptor.postHandle(request, response, this.handler, mv);
    147.             }
    148.         }
    149.     }
    150.     /**
    151.      * Trigger afterCompletion callbacks on the mapped HandlerInterceptors.
    152.      * Will just invoke afterCompletion for all interceptors whose preHandle invocation
    153.      * has successfully completed and returned true.
    154.      */
    155.     void triggerAfterCompletion(HttpServletRequest request, HttpServletResponse response, @Nullable Exception ex)
    156.             throws Exception {
    157.         HandlerInterceptor[] interceptors = getInterceptors();
    158.         if (!ObjectUtils.isEmpty(interceptors)) {
    159.             for (int i = this.interceptorIndex; i >= 0; i--) {
    160.                 HandlerInterceptor interceptor = interceptors[i];
    161.                 try {
    162.                     interceptor.afterCompletion(request, response, this.handler, ex);
    163.                 }
    164.                 catch (Throwable ex2) {
    165.                     logger.error("HandlerInterceptor.afterCompletion threw exception", ex2);
    166.                 }
    167.             }
    168.         }
    169.     }
    170.     /**
    171.      * Apply afterConcurrentHandlerStarted callback on mapped AsyncHandlerInterceptors.
    172.      */
    173.     void applyAfterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response) {
    174.         HandlerInterceptor[] interceptors = getInterceptors();
    175.         if (!ObjectUtils.isEmpty(interceptors)) {
    176.             for (int i = interceptors.length - 1; i >= 0; i--) {
    177.                 HandlerInterceptor interceptor = interceptors[i];
    178.                 if (interceptor instanceof AsyncHandlerInterceptor) {
    179.                     try {
    180.                         AsyncHandlerInterceptor asyncInterceptor = (AsyncHandlerInterceptor) interceptor;
    181.                         asyncInterceptor.afterConcurrentHandlingStarted(request, response, this.handler);
    182.                     }
    183.                     catch (Throwable ex) {
    184.                         if (logger.isErrorEnabled()) {
    185.                             logger.error("Interceptor [" + interceptor + "] failed in afterConcurrentHandlingStarted", ex);
    186.                         }
    187.                     }
    188.                 }
    189.             }
    190.         }
    191.     }
    192.     /**
    193.      * Delegates to the handler's {@code toString()} implementation.
    194.      */
    195.     @Override
    196.     public String toString() {
    197.         Object handler = getHandler();
    198.         StringBuilder sb = new StringBuilder();
    199.         sb.append("HandlerExecutionChain with [").append(handler).append("] and ");
    200.         if (this.interceptorList != null) {
    201.             sb.append(this.interceptorList.size());
    202.         }
    203.         else if (this.interceptors != null) {
    204.             sb.append(this.interceptors.length);
    205.         }
    206.         else {
    207.             sb.append(0);
    208.         }
    209.         return sb.append(" interceptors").toString();
    210.     }
    211. }
    复制代码
    View CodeHandlerExecutionChain对象包含一个处理器(handler)。这里的处理器是对控制器(controller)的包装,因为我们的控制器方法可能存在参数,那么处理器就可以读入HTTP和上下文的相关参数,然后再传递给控制器方法。而在控制器执行完成返回后,处理器又可以通过配置信息对控制器的返回结果进行处理。从这段描述中可以看出,处理器包含了控制器方法的逻辑,此外还有处理器的拦截器(interceptor),这样就能够通过拦截处理器进一步地增强处理器的功能。得到了处理器(handler),还需要去运行,但是我们有普通HTTP请求,也有按BeanName的请求,甚至是WebSocket的请求,所以它还需要一个适配器去运行HandlerExecutionChain对象包含的处理器,这就是HandlerAdapter接口定义的实现类。可以看到在Spring MVC中最常用的HandlerAdapter的实现类,这便是HttpRequestHandlerAdapter。通过请求的类型,DispatcherServlet就会找到它来执行Web请求的HandlerExecutionChain对象包含的内容,这样就能够执行我们的处理器(handler)了。只是HandlerAdapter运行HandlerExecutionChain对象这步还比较复杂,我们这里暂时不进行深入讨论,放到后面再谈。在处理器调用控制器时,它首先通过模型层得到数据,再放入数据模型中,最后将返回模型和视图(ModelAndView)对象,这里控制器设置的视图名称设置为“user/details”,这样就走到了视图解析器(ViewResolver),去解析视图逻辑名称了。在代码清单中可以看到视图解析器(ViewResolver)的自动初始化。为了定制InternalResourceViewResolver初始化,可以在配置文件application.properties中进行配置
  • 在Spring Boot的机制下定制InternalResourceViewResolver这个视图解析器的初始化,也就是在返回视图名称之后,它会以前缀(prefix)和后缀(suffix)以及视图名称组成全路径定位视图。例如,在控制器中返回的是“user/details”,那么它就会找到/WEB-INF/jsp/user/details.jsp作为视图(View)。严格地说,这一步也不是必需的,因为有些视图并不需要逻辑名称,在不需要的时候,就不再需要视图解析器工作了
  • 视图解析器定位到视图后,视图的作用是将数据模型(Model)渲染,这样就能够响应用户的请求。这一步就是视图将数据模型渲染(View)出来,用来展示给用户查看。按照我们控制器的返回,就是/WEB-INF/jsp/user/details.jsp作为我们的视图
 

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

温锦文欧普厨电及净水器总代理

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表