DispatcherServlet

来源:互联网 发布:apache hadoop yarn 编辑:程序博客网 时间:2024/06/05 10:45

DispatcherServlet源码分析:

public class DispatcherServlet extends FrameworkServlet {<span style="white-space:pre"></span>/**         * 定义了spring mvc各种处理器在bean factory中的key         * ps:handlerMapping、handlerAdapter、handlerExceptionResolver、viewResolver比较特殊,默认是用不到的,只有把相关的设置设置为false才起作用         */<span style="white-space:pre"></span>public static final String MULTIPART_RESOLVER_BEAN_NAME = "multipartResolver";<span style="white-space:pre"></span>public static final String LOCALE_RESOLVER_BEAN_NAME = "localeResolver";<span style="white-space:pre"></span>public static final String THEME_RESOLVER_BEAN_NAME = "themeResolver";<span style="white-space:pre"></span>public static final String HANDLER_MAPPING_BEAN_NAME = "handlerMapping";<span style="white-space:pre"></span>public static final String HANDLER_ADAPTER_BEAN_NAME = "handlerAdapter";<span style="white-space:pre"></span>public static final String HANDLER_EXCEPTION_RESOLVER_BEAN_NAME = "handlerExceptionResolver";<span style="white-space:pre"></span>public static final String REQUEST_TO_VIEW_NAME_TRANSLATOR_BEAN_NAME = "viewNameTranslator";<span style="white-space:pre"></span>public static final String VIEW_RESOLVER_BEAN_NAME = "viewResolver";<span style="white-space:pre"></span>public static final String FLASH_MAP_MANAGER_BEAN_NAME = "flashMapManager";<span style="white-space:pre"></span>/**<span style="white-space:pre"></span> * 获取ApplicationContext的key<span style="white-space:pre"></span> * 获取方法RequestContextUtils#getWebApplicationContext<span style="white-space:pre"></span> */<span style="white-space:pre"></span>public static final String WEB_APPLICATION_CONTEXT_ATTRIBUTE = DispatcherServlet.class.getName() + ".CONTEXT";<span style="white-space:pre"></span>/**<span style="white-space:pre"></span> * 获取当前spring mvc各种处理器的key<span style="white-space:pre"></span> */<span style="white-space:pre"></span>public static final String LOCALE_RESOLVER_ATTRIBUTE = DispatcherServlet.class.getName() + ".LOCALE_RESOLVER";<span style="white-space:pre"></span>public static final String THEME_RESOLVER_ATTRIBUTE = DispatcherServlet.class.getName() + ".THEME_RESOLVER";<span style="white-space:pre"></span>public static final String THEME_SOURCE_ATTRIBUTE = DispatcherServlet.class.getName() + ".THEME_SOURCE";<span style="white-space:pre"></span>public static final String INPUT_FLASH_MAP_ATTRIBUTE = DispatcherServlet.class.getName() + ".INPUT_FLASH_MAP";<span style="white-space:pre"></span>public static final String OUTPUT_FLASH_MAP_ATTRIBUTE = DispatcherServlet.class.getName() + ".OUTPUT_FLASH_MAP";<span style="white-space:pre"></span>public static final String FLASH_MAP_MANAGER_ATTRIBUTE = DispatcherServlet.class.getName() + ".FLASH_MAP_MANAGER";<span style="white-space:pre"></span>/** 当映射找不到时的日志. */<span style="white-space:pre"></span>public static final String PAGE_NOT_FOUND_LOG_CATEGORY = "org.springframework.web.servlet.PageNotFound";<span style="white-space:pre"></span>/**<span style="white-space:pre"></span> * spring mvc各种处理器的默认配置<span style="white-space:pre"></span> */<span style="white-space:pre"></span>private static final String DEFAULT_STRATEGIES_PATH = "DispatcherServlet.properties";<span style="white-space:pre"></span>/** 定义找不到映射的log. */<span style="white-space:pre"></span>protected static final Log pageNotFoundLogger = LogFactory.getLog(PAGE_NOT_FOUND_LOG_CATEGORY);<span style="white-space:pre"></span>private static final UrlPathHelper urlPathHelper = new UrlPathHelper();<span style="white-space:pre"></span>private static final Properties defaultStrategies;<span style="white-space:pre"></span>static {<span style="white-space:pre"></span>// 读取配置文件信息(包含了spring mvc各种默认的处理器)<span style="white-space:pre"></span>try {<span style="white-space:pre"></span>ClassPathResource resource = new ClassPathResource(DEFAULT_STRATEGIES_PATH, DispatcherServlet.class);<span style="white-space:pre"></span>defaultStrategies = PropertiesLoaderUtils.loadProperties(resource);<span style="white-space:pre"></span>}<span style="white-space:pre"></span>catch (IOException ex) {<span style="white-space:pre"></span>throw new IllegalStateException("Could not load 'DispatcherServlet.properties': " + ex.getMessage());<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}<span style="white-space:pre"></span>/** 当为true时,加载所有集成了HandlerMapping的bean,当为false时,只加载名为“handlerMapping”的bean */<span style="white-space:pre"></span>private boolean detectAllHandlerMappings = true;<span style="white-space:pre"></span>/** 同理detectAllHandlerMappings(handlerAdapter) */<span style="white-space:pre"></span>private boolean detectAllHandlerAdapters = true;<span style="white-space:pre"></span>/** 同理detectAllHandlerMappings(handlerExceptionResolver) */<span style="white-space:pre"></span>private boolean detectAllHandlerExceptionResolvers = true;<span style="white-space:pre"></span>/** 同理detectAllHandlerMappings(viewResolver) */<span style="white-space:pre"></span>private boolean detectAllViewResolvers = true;<span style="white-space:pre"></span>/** 请求处理后是否清空 */<span style="white-space:pre"></span>private boolean cleanupAfterInclude = true;<span style="white-space:pre"></span>/** 定义spring mvc各种处理器对象 */<span style="white-space:pre"></span>private MultipartResolver multipartResolver;<span style="white-space:pre"></span>private LocaleResolver localeResolver;<span style="white-space:pre"></span>private ThemeResolver themeResolver;<span style="white-space:pre"></span>private List<HandlerMapping> handlerMappings;<span style="white-space:pre"></span>private List<HandlerAdapter> handlerAdapters;<span style="white-space:pre"></span>private List<HandlerExceptionResolver> handlerExceptionResolvers;<span style="white-space:pre"></span>private RequestToViewNameTranslator viewNameTranslator;<span style="white-space:pre"></span>private FlashMapManager flashMapManager;<span style="white-space:pre"></span>private List<ViewResolver> viewResolvers;<span style="white-space:pre"></span>/**<span style="white-space:pre"></span> * 默认WebApplicationContext为XmlWebApplicationContext<span style="white-space:pre"></span> */<span style="white-space:pre"></span>public DispatcherServlet() {<span style="white-space:pre"></span>super();<span style="white-space:pre"></span>}<span style="white-space:pre"></span>/**         * 设置WebApplicationContext         */<span style="white-space:pre"></span>public DispatcherServlet(WebApplicationContext webApplicationContext) {<span style="white-space:pre"></span>super(webApplicationContext);<span style="white-space:pre"></span>}<span style="white-space:pre"></span>public void setDetectAllHandlerMappings(boolean detectAllHandlerMappings) {<span style="white-space:pre"></span>this.detectAllHandlerMappings = detectAllHandlerMappings;<span style="white-space:pre"></span>}<span style="white-space:pre"></span>public void setDetectAllHandlerAdapters(boolean detectAllHandlerAdapters) {<span style="white-space:pre"></span>this.detectAllHandlerAdapters = detectAllHandlerAdapters;<span style="white-space:pre"></span>}<span style="white-space:pre"></span>public void setDetectAllHandlerExceptionResolvers(boolean detectAllHandlerExceptionResolvers) {<span style="white-space:pre"></span>this.detectAllHandlerExceptionResolvers = detectAllHandlerExceptionResolvers;<span style="white-space:pre"></span>}<span style="white-space:pre"></span>public void setDetectAllViewResolvers(boolean detectAllViewResolvers) {<span style="white-space:pre"></span>this.detectAllViewResolvers = detectAllViewResolvers;<span style="white-space:pre"></span>}<span style="white-space:pre"></span>public void setCleanupAfterInclude(boolean cleanupAfterInclude) {<span style="white-space:pre"></span>this.cleanupAfterInclude = cleanupAfterInclude;<span style="white-space:pre"></span>}<span style="white-space:pre"></span>/**<span style="white-space:pre"></span> * 从DispatcherServlet的继承关系看:DispatcherServlet->FrameworkServlet         *                                 ->HttpServletBean->HttpServlet         * 初始化的过程是这样的HttpServletBean#init ->          *      FrameworkServlet#initServletBean -> DispatherServlet#onRefresh<span style="white-space:pre"></span> */<span style="white-space:pre"></span>@Override<span style="white-space:pre"></span>protected void onRefresh(ApplicationContext context) {<span style="white-space:pre"></span>initStrategies(context);<span style="white-space:pre"></span>}<span style="white-space:pre"></span>/**<span style="white-space:pre"></span> * 初始化spring mvc的各种处理器<span style="white-space:pre"></span> * <p>May be overridden in subclasses in order to initialize further strategy objects.<span style="white-space:pre"></span> */<span style="white-space:pre"></span>protected void initStrategies(ApplicationContext context) {<span style="white-space:pre"></span>initMultipartResolver(context);<span style="white-space:pre"></span>initLocaleResolver(context);<span style="white-space:pre"></span>initThemeResolver(context);<span style="white-space:pre"></span>initHandlerMappings(context);<span style="white-space:pre"></span>initHandlerAdapters(context);<span style="white-space:pre"></span>initHandlerExceptionResolvers(context);<span style="white-space:pre"></span>initRequestToViewNameTranslator(context);<span style="white-space:pre"></span>initViewResolvers(context);<span style="white-space:pre"></span>initFlashMapManager(context);<span style="white-space:pre"></span>}<span style="white-space:pre"></span>/**<span style="white-space:pre"></span> * 初始化MultipartResolver,如果没有,则不提供此处理器<span style="white-space:pre"></span> */<span style="white-space:pre"></span>private void initMultipartResolver(ApplicationContext context) {<span style="white-space:pre"></span>try {<span style="white-space:pre"></span>this.multipartResolver = context.getBean(MULTIPART_RESOLVER_BEAN_NAME, MultipartResolver.class);<span style="white-space:pre"></span>if (logger.isDebugEnabled()) {<span style="white-space:pre"></span>logger.debug("Using MultipartResolver [" + this.multipartResolver + "]");<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}<span style="white-space:pre"></span>catch (NoSuchBeanDefinitionException ex) {<span style="white-space:pre"></span>// Default is no multipart resolver.<span style="white-space:pre"></span>this.multipartResolver = null;<span style="white-space:pre"></span>if (logger.isDebugEnabled()) {<span style="white-space:pre"></span>logger.debug("Unable to locate MultipartResolver with name '" + MULTIPART_RESOLVER_BEAN_NAME +<span style="white-space:pre"></span>"': no multipart request handling provided");<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}<span style="white-space:pre"></span>/**<span style="white-space:pre"></span> * 初始化LocaleResolver,如果没有,则使用默认的LocalResolver:AcceptHeaderLocaleResolver<span style="white-space:pre"></span> */<span style="white-space:pre"></span>private void initLocaleResolver(ApplicationContext context) {<span style="white-space:pre"></span>try {<span style="white-space:pre"></span>this.localeResolver = context.getBean(LOCALE_RESOLVER_BEAN_NAME, LocaleResolver.class);<span style="white-space:pre"></span>if (logger.isDebugEnabled()) {<span style="white-space:pre"></span>logger.debug("Using LocaleResolver [" + this.localeResolver + "]");<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}<span style="white-space:pre"></span>catch (NoSuchBeanDefinitionException ex) {<span style="white-space:pre"></span>// We need to use the default.<span style="white-space:pre"></span>this.localeResolver = getDefaultStrategy(context, LocaleResolver.class);<span style="white-space:pre"></span>if (logger.isDebugEnabled()) {<span style="white-space:pre"></span>logger.debug("Unable to locate LocaleResolver with name '" + LOCALE_RESOLVER_BEAN_NAME +<span style="white-space:pre"></span>"': using default [" + this.localeResolver + "]");<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}<span style="white-space:pre"></span>/**<span style="white-space:pre"></span> * 初始化ThemeResolver,如果没有,<span style="white-space:pre"></span> * 则使用默认的ThemeResolver:FixedThemeResolver<span style="white-space:pre"></span> */<span style="white-space:pre"></span>private void initThemeResolver(ApplicationContext context) {<span style="white-space:pre"></span>try {<span style="white-space:pre"></span>this.themeResolver = context.getBean(THEME_RESOLVER_BEAN_NAME, ThemeResolver.class);<span style="white-space:pre"></span>if (logger.isDebugEnabled()) {<span style="white-space:pre"></span>logger.debug("Using ThemeResolver [" + this.themeResolver + "]");<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}<span style="white-space:pre"></span>catch (NoSuchBeanDefinitionException ex) {<span style="white-space:pre"></span>// We need to use the default.<span style="white-space:pre"></span>this.themeResolver = getDefaultStrategy(context, ThemeResolver.class);<span style="white-space:pre"></span>if (logger.isDebugEnabled()) {<span style="white-space:pre"></span>logger.debug(<span style="white-space:pre"></span>"Unable to locate ThemeResolver with name '" + THEME_RESOLVER_BEAN_NAME + "': using default [" +<span style="white-space:pre"></span>this.themeResolver + "]");<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}<span style="white-space:pre"></span>/**<span style="white-space:pre"></span> * 初始化HandlerMapping<span style="white-space:pre"></span> * detectAllHandlerMappings=true时,加载所有的HandlerMapping,若为false时,加载指定的HandlerMapping<span style="white-space:pre"></span> * 如果都没有,则使用默认的:BeanNameUrlHandlerMapping、DefaultAnnotationHandlerMapping<span style="white-space:pre"></span> */<span style="white-space:pre"></span>private void initHandlerMappings(ApplicationContext context) {<span style="white-space:pre"></span>this.handlerMappings = null;<span style="white-space:pre"></span>if (this.detectAllHandlerMappings) {<span style="white-space:pre"></span>// Find all HandlerMappings in the ApplicationContext, including ancestor contexts.<span style="white-space:pre"></span>Map<String, HandlerMapping> matchingBeans =<span style="white-space:pre"></span>BeanFactoryUtils.beansOfTypeIncludingAncestors(context, HandlerMapping.class, true, false);<span style="white-space:pre"></span>if (!matchingBeans.isEmpty()) {<span style="white-space:pre"></span>this.handlerMappings = new ArrayList<HandlerMapping>(matchingBeans.values());<span style="white-space:pre"></span>// We keep HandlerMappings in sorted order.<span style="white-space:pre"></span>OrderComparator.sort(this.handlerMappings);<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}<span style="white-space:pre"></span>else {<span style="white-space:pre"></span>try {<span style="white-space:pre"></span>HandlerMapping hm = context.getBean(HANDLER_MAPPING_BEAN_NAME, HandlerMapping.class);<span style="white-space:pre"></span>this.handlerMappings = Collections.singletonList(hm);<span style="white-space:pre"></span>}<span style="white-space:pre"></span>catch (NoSuchBeanDefinitionException ex) {<span style="white-space:pre"></span>// Ignore, we'll add a default HandlerMapping later.<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}<span style="white-space:pre"></span>// Ensure we have at least one HandlerMapping, by registering<span style="white-space:pre"></span>// a default HandlerMapping if no other mappings are found.<span style="white-space:pre"></span>if (this.handlerMappings == null) {<span style="white-space:pre"></span>this.handlerMappings = getDefaultStrategies(context, HandlerMapping.class);<span style="white-space:pre"></span>if (logger.isDebugEnabled()) {<span style="white-space:pre"></span>logger.debug("No HandlerMappings found in servlet '" + getServletName() + "': using default");<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}<span style="white-space:pre"></span>/**<span style="white-space:pre"></span> * 初始化HandlerAdapter<span style="white-space:pre"></span> * detectAllHandlerAdapters=true时,加载所有的HandlerAdapter,若为false时,加载指定的HandlerAdapter<span style="white-space:pre"></span> * 如果都没有,则使用默认的:HttpRequestHandlerAdapter、SimpleControllerHandlerAdapter、AnnotationMethodHandlerAdapter<span style="white-space:pre"></span> */<span style="white-space:pre"></span>private void initHandlerAdapters(ApplicationContext context) {<span style="white-space:pre"></span>this.handlerAdapters = null;<span style="white-space:pre"></span>if (this.detectAllHandlerAdapters) {<span style="white-space:pre"></span>// Find all HandlerAdapters in the ApplicationContext, including ancestor contexts.<span style="white-space:pre"></span>Map<String, HandlerAdapter> matchingBeans =<span style="white-space:pre"></span>BeanFactoryUtils.beansOfTypeIncludingAncestors(context, HandlerAdapter.class, true, false);<span style="white-space:pre"></span>if (!matchingBeans.isEmpty()) {<span style="white-space:pre"></span>this.handlerAdapters = new ArrayList<HandlerAdapter>(matchingBeans.values());<span style="white-space:pre"></span>// We keep HandlerAdapters in sorted order.<span style="white-space:pre"></span>OrderComparator.sort(this.handlerAdapters);<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}<span style="white-space:pre"></span>else {<span style="white-space:pre"></span>try {<span style="white-space:pre"></span>HandlerAdapter ha = context.getBean(HANDLER_ADAPTER_BEAN_NAME, HandlerAdapter.class);<span style="white-space:pre"></span>this.handlerAdapters = Collections.singletonList(ha);<span style="white-space:pre"></span>}<span style="white-space:pre"></span>catch (NoSuchBeanDefinitionException ex) {<span style="white-space:pre"></span>// Ignore, we'll add a default HandlerAdapter later.<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}<span style="white-space:pre"></span>// Ensure we have at least some HandlerAdapters, by registering<span style="white-space:pre"></span>// default HandlerAdapters if no other adapters are found.<span style="white-space:pre"></span>if (this.handlerAdapters == null) {<span style="white-space:pre"></span>this.handlerAdapters = getDefaultStrategies(context, HandlerAdapter.class);<span style="white-space:pre"></span>if (logger.isDebugEnabled()) {<span style="white-space:pre"></span>logger.debug("No HandlerAdapters found in servlet '" + getServletName() + "': using default");<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}<span style="white-space:pre"></span>/**<span style="white-space:pre"></span> * 初始化HandlerExceptionResolvers<span style="white-space:pre"></span> * detectAllHandlerExceptionResolvers=true时,加载所有的HandlerExceptionResolvers,若为false时,加载指定的HandlerExceptionResolvers<span style="white-space:pre"></span> * 如果都没有,则使用默认的:AnnotationMethodHandlerExceptionResolver、ResponseStatusExceptionResolver、DefaultHandlerExceptionResolver<span style="white-space:pre"></span> */<span style="white-space:pre"></span>private void initHandlerExceptionResolvers(ApplicationContext context) {<span style="white-space:pre"></span>this.handlerExceptionResolvers = null;<span style="white-space:pre"></span>if (this.detectAllHandlerExceptionResolvers) {<span style="white-space:pre"></span>// Find all HandlerExceptionResolvers in the ApplicationContext, including ancestor contexts.<span style="white-space:pre"></span>Map<String, HandlerExceptionResolver> matchingBeans = BeanFactoryUtils<span style="white-space:pre"></span>.beansOfTypeIncludingAncestors(context, HandlerExceptionResolver.class, true, false);<span style="white-space:pre"></span>if (!matchingBeans.isEmpty()) {<span style="white-space:pre"></span>this.handlerExceptionResolvers = new ArrayList<HandlerExceptionResolver>(matchingBeans.values());<span style="white-space:pre"></span>// We keep HandlerExceptionResolvers in sorted order.<span style="white-space:pre"></span>OrderComparator.sort(this.handlerExceptionResolvers);<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}<span style="white-space:pre"></span>else {<span style="white-space:pre"></span>try {<span style="white-space:pre"></span>HandlerExceptionResolver her =<span style="white-space:pre"></span>context.getBean(HANDLER_EXCEPTION_RESOLVER_BEAN_NAME, HandlerExceptionResolver.class);<span style="white-space:pre"></span>this.handlerExceptionResolvers = Collections.singletonList(her);<span style="white-space:pre"></span>}<span style="white-space:pre"></span>catch (NoSuchBeanDefinitionException ex) {<span style="white-space:pre"></span>// Ignore, no HandlerExceptionResolver is fine too.<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}<span style="white-space:pre"></span>// Ensure we have at least some HandlerExceptionResolvers, by registering<span style="white-space:pre"></span>// default HandlerExceptionResolvers if no other resolvers are found.<span style="white-space:pre"></span>if (this.handlerExceptionResolvers == null) {<span style="white-space:pre"></span>this.handlerExceptionResolvers = getDefaultStrategies(context, HandlerExceptionResolver.class);<span style="white-space:pre"></span>if (logger.isDebugEnabled()) {<span style="white-space:pre"></span>logger.debug("No HandlerExceptionResolvers found in servlet '" + getServletName() + "': using default");<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}<span style="white-space:pre"></span>/**<span style="white-space:pre"></span> * 初始化RequestToViewNameTranslator<span style="white-space:pre"></span> * 如果没有,则使用默认的:DefaultRequestToViewNameTranslator<span style="white-space:pre"></span> */<span style="white-space:pre"></span>private void initRequestToViewNameTranslator(ApplicationContext context) {<span style="white-space:pre"></span>try {<span style="white-space:pre"></span>this.viewNameTranslator =<span style="white-space:pre"></span>context.getBean(REQUEST_TO_VIEW_NAME_TRANSLATOR_BEAN_NAME, RequestToViewNameTranslator.class);<span style="white-space:pre"></span>if (logger.isDebugEnabled()) {<span style="white-space:pre"></span>logger.debug("Using RequestToViewNameTranslator [" + this.viewNameTranslator + "]");<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}<span style="white-space:pre"></span>catch (NoSuchBeanDefinitionException ex) {<span style="white-space:pre"></span>// We need to use the default.<span style="white-space:pre"></span>this.viewNameTranslator = getDefaultStrategy(context, RequestToViewNameTranslator.class);<span style="white-space:pre"></span>if (logger.isDebugEnabled()) {<span style="white-space:pre"></span>logger.debug("Unable to locate RequestToViewNameTranslator with name '" +<span style="white-space:pre"></span>REQUEST_TO_VIEW_NAME_TRANSLATOR_BEAN_NAME + "': using default [" + this.viewNameTranslator +<span style="white-space:pre"></span>"]");<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}        /**<span style="white-space:pre"></span> * 初始化ViewResolver<span style="white-space:pre"></span> * detectAllViewResolvers=true时,加载所有的ViewResolver,若为false时,加载指定的ViewResolver<span style="white-space:pre"></span> * 如果都没有,则使用默认的:InternalResourceViewResolver<span style="white-space:pre"></span> */<span style="white-space:pre"></span>private void initViewResolvers(ApplicationContext context) {<span style="white-space:pre"></span>this.viewResolvers = null;<span style="white-space:pre"></span>if (this.detectAllViewResolvers) {<span style="white-space:pre"></span>// Find all ViewResolvers in the ApplicationContext, including ancestor contexts.<span style="white-space:pre"></span>Map<String, ViewResolver> matchingBeans =<span style="white-space:pre"></span>BeanFactoryUtils.beansOfTypeIncludingAncestors(context, ViewResolver.class, true, false);<span style="white-space:pre"></span>if (!matchingBeans.isEmpty()) {<span style="white-space:pre"></span>this.viewResolvers = new ArrayList<ViewResolver>(matchingBeans.values());<span style="white-space:pre"></span>// We keep ViewResolvers in sorted order.<span style="white-space:pre"></span>OrderComparator.sort(this.viewResolvers);<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}<span style="white-space:pre"></span>else {<span style="white-space:pre"></span>try {<span style="white-space:pre"></span>ViewResolver vr = context.getBean(VIEW_RESOLVER_BEAN_NAME, ViewResolver.class);<span style="white-space:pre"></span>this.viewResolvers = Collections.singletonList(vr);<span style="white-space:pre"></span>}<span style="white-space:pre"></span>catch (NoSuchBeanDefinitionException ex) {<span style="white-space:pre"></span>// Ignore, we'll add a default ViewResolver later.<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}<span style="white-space:pre"></span>// Ensure we have at least one ViewResolver, by registering<span style="white-space:pre"></span>// a default ViewResolver if no other resolvers are found.<span style="white-space:pre"></span>if (this.viewResolvers == null) {<span style="white-space:pre"></span>this.viewResolvers = getDefaultStrategies(context, ViewResolver.class);<span style="white-space:pre"></span>if (logger.isDebugEnabled()) {<span style="white-space:pre"></span>logger.debug("No ViewResolvers found in servlet '" + getServletName() + "': using default");<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}<span style="white-space:pre"></span>/**<span style="white-space:pre"></span> * 初始化FlashMapManager<span style="white-space:pre"></span> * 如果没有,则使用默认的:SessionFlashMapManager<span style="white-space:pre"></span> */<span style="white-space:pre"></span>private void initFlashMapManager(ApplicationContext context) {<span style="white-space:pre"></span>try {<span style="white-space:pre"></span>this.flashMapManager =<span style="white-space:pre"></span>context.getBean(FLASH_MAP_MANAGER_BEAN_NAME, FlashMapManager.class);<span style="white-space:pre"></span>if (logger.isDebugEnabled()) {<span style="white-space:pre"></span>logger.debug("Using FlashMapManager [" + this.flashMapManager + "]");<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}<span style="white-space:pre"></span>catch (NoSuchBeanDefinitionException ex) {<span style="white-space:pre"></span>// We need to use the default.<span style="white-space:pre"></span>this.flashMapManager = getDefaultStrategy(context, FlashMapManager.class);<span style="white-space:pre"></span>if (logger.isDebugEnabled()) {<span style="white-space:pre"></span>logger.debug("Unable to locate FlashMapManager with name '" +<span style="white-space:pre"></span>FLASH_MAP_MANAGER_BEAN_NAME + "': using default [" + this.flashMapManager + "]");<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}<span style="white-space:pre"></span>/**<span style="white-space:pre"></span> * 获取ThemeSource<span style="white-space:pre"></span> */<span style="white-space:pre"></span>public final ThemeSource getThemeSource() {<span style="white-space:pre"></span>if (getWebApplicationContext() instanceof ThemeSource) {<span style="white-space:pre"></span>return (ThemeSource) getWebApplicationContext();<span style="white-space:pre"></span>}<span style="white-space:pre"></span>else {<span style="white-space:pre"></span>return null;<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}<span style="white-space:pre"></span>/**<span style="white-space:pre"></span> * 获取MulitpartResolver<span style="white-space:pre"></span> */<span style="white-space:pre"></span>public final MultipartResolver getMultipartResolver() {<span style="white-space:pre"></span>return this.multipartResolver;<span style="white-space:pre"></span>}<span style="white-space:pre"></span>/**<span style="white-space:pre"></span> * 获取默认的处理器.<span style="white-space:pre"></span> */<span style="white-space:pre"></span>protected <T> T getDefaultStrategy(ApplicationContext context, Class<T> strategyInterface) {<span style="white-space:pre"></span>List<T> strategies = getDefaultStrategies(context, strategyInterface);<span style="white-space:pre"></span>if (strategies.size() != 1) {<span style="white-space:pre"></span>throw new BeanInitializationException(<span style="white-space:pre"></span>"DispatcherServlet needs exactly 1 strategy for interface [" + strategyInterface.getName() + "]");<span style="white-space:pre"></span>}<span style="white-space:pre"></span>return strategies.get(0);<span style="white-space:pre"></span>}<span style="white-space:pre"></span>/**<span style="white-space:pre"></span> * 获取默认配置.<span style="white-space:pre"></span> */<span style="white-space:pre"></span>@SuppressWarnings("unchecked")<span style="white-space:pre"></span>protected <T> List<T> getDefaultStrategies(ApplicationContext context, Class<T> strategyInterface) {<span style="white-space:pre"></span>String key = strategyInterface.getName();                // 从配置文件中获取类名<span style="white-space:pre"></span>String value = defaultStrategies.getProperty(key);<span style="white-space:pre"></span>if (value != null) {                        // 分割<span style="white-space:pre"></span>String[] classNames = StringUtils.commaDelimitedListToStringArray(value);<span style="white-space:pre"></span>List<T> strategies = new ArrayList<T>(classNames.length);<span style="white-space:pre"></span>for (String className : classNames) {<span style="white-space:pre"></span>try {<span style="white-space:pre"></span>Class<?> clazz = ClassUtils.forName(className, DispatcherServlet.class.getClassLoader());                                        // 创建bean<span style="white-space:pre"></span>Object strategy = createDefaultStrategy(context, clazz);<span style="white-space:pre"></span>strategies.add((T) strategy);<span style="white-space:pre"></span>}<span style="white-space:pre"></span>catch (ClassNotFoundException ex) {<span style="white-space:pre"></span>throw new BeanInitializationException(<span style="white-space:pre"></span>"Could not find DispatcherServlet's default strategy class [" + className +<span style="white-space:pre"></span>"] for interface [" + key + "]", ex);<span style="white-space:pre"></span>}<span style="white-space:pre"></span>catch (LinkageError err) {<span style="white-space:pre"></span>throw new BeanInitializationException(<span style="white-space:pre"></span>"Error loading DispatcherServlet's default strategy class [" + className +<span style="white-space:pre"></span>"] for interface [" + key + "]: problem with class file or dependent class", err);<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}<span style="white-space:pre"></span>return strategies;<span style="white-space:pre"></span>}<span style="white-space:pre"></span>else {<span style="white-space:pre"></span>return new LinkedList<T>();<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}<span style="white-space:pre"></span>/**<span style="white-space:pre"></span> * 创建bean.<span style="white-space:pre"></span> */<span style="white-space:pre"></span>protected Object createDefaultStrategy(ApplicationContext context, Class<?> clazz) {<span style="white-space:pre"></span>return context.getAutowireCapableBeanFactory().createBean(clazz);<span style="white-space:pre"></span>}<span style="white-space:pre"></span>/**<span style="white-space:pre"></span> * doService是一个调度方法,每一个请求发生时,先执行此方法<span style="white-space:pre"></span> * for the actual dispatching.<span style="white-space:pre"></span> */<span style="white-space:pre"></span>@Override<span style="white-space:pre"></span>protected void doService(HttpServletRequest request, HttpServletResponse response) throws Exception {<span style="white-space:pre"></span>if (logger.isDebugEnabled()) {<span style="white-space:pre"></span>String requestUri = urlPathHelper.getRequestUri(request);<span style="white-space:pre"></span>logger.debug("DispatcherServlet with name '" + getServletName() + "' processing " + request.getMethod() +<span style="white-space:pre"></span>" request for [" + requestUri + "]");<span style="white-space:pre"></span>}<span style="white-space:pre"></span>// 是否存在客户当次请求信息<span style="white-space:pre"></span>Map<String, Object> attributesSnapshot = null;<span style="white-space:pre"></span>if (WebUtils.isIncludeRequest(request)) { // 判断是否为转发请求<span style="white-space:pre"></span>logger.debug("Taking snapshot of request attributes before include");<span style="white-space:pre"></span>attributesSnapshot = new HashMap<String, Object>();<span style="white-space:pre"></span>Enumeration<?> attrNames = request.getAttributeNames();<span style="white-space:pre"></span>while (attrNames.hasMoreElements()) {<span style="white-space:pre"></span>String attrName = (String) attrNames.nextElement();<span style="white-space:pre"></span>if (this.cleanupAfterInclude || attrName.startsWith("org.springframework.web.servlet")) {<span style="white-space:pre"></span>attributesSnapshot.put(attrName, request.getAttribute(attrName));<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}<span style="white-space:pre"></span>// 设置属性<span style="white-space:pre"></span>request.setAttribute(WEB_APPLICATION_CONTEXT_ATTRIBUTE, getWebApplicationContext());<span style="white-space:pre"></span>request.setAttribute(LOCALE_RESOLVER_ATTRIBUTE, this.localeResolver);<span style="white-space:pre"></span>request.setAttribute(THEME_RESOLVER_ATTRIBUTE, this.themeResolver);<span style="white-space:pre"></span>request.setAttribute(THEME_SOURCE_ATTRIBUTE, getThemeSource());<span style="white-space:pre"></span>FlashMap inputFlashMap = this.flashMapManager.retrieveAndUpdate(request, response);<span style="white-space:pre"></span>if (inputFlashMap != null) {<span style="white-space:pre"></span>request.setAttribute(INPUT_FLASH_MAP_ATTRIBUTE, Collections.unmodifiableMap(inputFlashMap));<span style="white-space:pre"></span>}<span style="white-space:pre"></span>request.setAttribute(OUTPUT_FLASH_MAP_ATTRIBUTE, new FlashMap());<span style="white-space:pre"></span>request.setAttribute(FLASH_MAP_MANAGER_ATTRIBUTE, this.flashMapManager);<span style="white-space:pre"></span>try {                        // 分发<span style="white-space:pre"></span>doDispatch(request, response);<span style="white-space:pre"></span>}<span style="white-space:pre"></span>finally {<span style="white-space:pre"></span>// 报错参数在之后的转发中.<span style="white-space:pre"></span>if (attributesSnapshot != null) {<span style="white-space:pre"></span>restoreAttributesAfterInclude(request, attributesSnapshot);<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}<span style="white-space:pre"></span>/**<span style="white-space:pre"></span> * Process the actual dispatching to the handler.<span style="white-space:pre"></span> * <p>The handler will be obtained by applying the servlet's HandlerMappings in order.<span style="white-space:pre"></span> * The HandlerAdapter will be obtained by querying the servlet's installed HandlerAdapters<span style="white-space:pre"></span> * to find the first that supports the handler class.<span style="white-space:pre"></span> * <p>All HTTP methods are handled by this method. It's up to HandlerAdapters or handlers<span style="white-space:pre"></span> * themselves to decide which methods are acceptable.<span style="white-space:pre"></span> * @param request current HTTP request<span style="white-space:pre"></span> * @param response current HTTP response<span style="white-space:pre"></span> * @throws Exception in case of any kind of processing failure<span style="white-space:pre"></span> */<span style="white-space:pre"></span>protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {<span style="white-space:pre"></span>HttpServletRequest processedRequest = request;<span style="white-space:pre"></span>HandlerExecutionChain mappedHandler = null;<span style="white-space:pre"></span>int interceptorIndex = -1;<span style="white-space:pre"></span>try {<span style="white-space:pre"></span>ModelAndView mv;<span style="white-space:pre"></span>boolean errorView = false;<span style="white-space:pre"></span>try {                                // 检查是否是请求是否是multipart(如文件上传),如果是将通过MultipartResolver解析<span style="white-space:pre"></span>processedRequest = checkMultipart(request);<span style="white-space:pre"></span>// 请求到处理器(页面控制器)的映射,通过HandlerMapping进行映射.<span style="white-space:pre"></span>mappedHandler = getHandler(processedRequest, false);<span style="white-space:pre"></span>if (mappedHandler == null || mappedHandler.getHandler() == null) {<span style="white-space:pre"></span>noHandlerFound(processedRequest, response);<span style="white-space:pre"></span>return;<span style="white-space:pre"></span>}<span style="white-space:pre"></span>// 处理器适配,即将我们的处理器包装成相应的适配器(从而支持多种类型的处理器)  <span style="white-space:pre"></span>HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());                                // Not Modified缓存支持.<span style="white-space:pre"></span>String method = request.getMethod();<span style="white-space:pre"></span>boolean isGet = "GET".equals(method);<span style="white-space:pre"></span>if (isGet || "HEAD".equals(method)) {<span style="white-space:pre"></span>long lastModified = ha.getLastModified(request, mappedHandler.getHandler());<span style="white-space:pre"></span>if (logger.isDebugEnabled()) {<span style="white-space:pre"></span>String requestUri = urlPathHelper.getRequestUri(request);<span style="white-space:pre"></span>logger.debug("Last-Modified value for [" + requestUri + "] is: " + lastModified);<span style="white-space:pre"></span>}<span style="white-space:pre"></span>if (new ServletWebRequest(request, response).checkNotModified(lastModified) && isGet) {<span style="white-space:pre"></span>return;<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}<span style="white-space:pre"></span>// 执行处理器相关的拦截器的预处理(HandlerInterceptor.preHandle).<span style="white-space:pre"></span>HandlerInterceptor[] interceptors = mappedHandler.getInterceptors();<span style="white-space:pre"></span>if (interceptors != null) {<span style="white-space:pre"></span>for (int i = 0; i < interceptors.length; i++) {<span style="white-space:pre"></span>HandlerInterceptor interceptor = interceptors[i];<span style="white-space:pre"></span>if (!interceptor.preHandle(processedRequest, response, mappedHandler.getHandler())) {<span style="white-space:pre"></span>triggerAfterCompletion(mappedHandler, interceptorIndex, processedRequest, response, null);<span style="white-space:pre"></span>return;<span style="white-space:pre"></span>}<span style="white-space:pre"></span>interceptorIndex = i;<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}<span style="white-space:pre"></span>// 由适配器执行处理器(调用处理器相应功能处理方法).<span style="white-space:pre"></span>mv = ha.handle(processedRequest, response, mappedHandler.getHandler());<span style="white-space:pre"></span>// 如果mv==null,设置为默认的<span style="white-space:pre"></span>if (mv != null && !mv.hasView()) {<span style="white-space:pre"></span>mv.setViewName(getDefaultViewName(request));<span style="white-space:pre"></span>}<span style="white-space:pre"></span>// 执行处理器相关的拦截器的后处理(HandlerInterceptor.postHandle)<span style="white-space:pre"></span>if (interceptors != null) {<span style="white-space:pre"></span>for (int i = interceptors.length - 1; i >= 0; i--) {<span style="white-space:pre"></span>HandlerInterceptor interceptor = interceptors[i];<span style="white-space:pre"></span>interceptor.postHandle(processedRequest, response, mappedHandler.getHandler(), mv);<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}<span style="white-space:pre"></span>catch (ModelAndViewDefiningException ex) {<span style="white-space:pre"></span>logger.debug("ModelAndViewDefiningException encountered", ex);<span style="white-space:pre"></span>mv = ex.getModelAndView();<span style="white-space:pre"></span>}<span style="white-space:pre"></span>catch (Exception ex) {<span style="white-space:pre"></span>Object handler = (mappedHandler != null ? mappedHandler.getHandler() : null);<span style="white-space:pre"></span>mv = processHandlerException(processedRequest, response, handler, ex);<span style="white-space:pre"></span>errorView = (mv != null);<span style="white-space:pre"></span>}<span style="white-space:pre"></span>// 解析视图并进行视图的渲染<span style="white-space:pre"></span>if (mv != null && !mv.wasCleared()) {<span style="white-space:pre"></span>render(mv, processedRequest, response);<span style="white-space:pre"></span>if (errorView) {<span style="white-space:pre"></span>WebUtils.clearErrorRequestAttributes(request);<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}<span style="white-space:pre"></span>else {<span style="white-space:pre"></span>if (logger.isDebugEnabled()) {<span style="white-space:pre"></span>logger.debug("Null ModelAndView returned to DispatcherServlet with name '" + getServletName() +<span style="white-space:pre"></span>"': assuming HandlerAdapter completed request handling");<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}<span style="white-space:pre"></span>// T执行处理器相关的拦截器的完成后处理(HandlerInterceptor.afterCompletion)<span style="white-space:pre"></span>triggerAfterCompletion(mappedHandler, interceptorIndex, processedRequest, response, null);<span style="white-space:pre"></span>}<span style="white-space:pre"></span>catch (Exception ex) {<span style="white-space:pre"></span>// Trigger after-completion for thrown exception.<span style="white-space:pre"></span>triggerAfterCompletion(mappedHandler, interceptorIndex, processedRequest, response, ex);<span style="white-space:pre"></span>throw ex;<span style="white-space:pre"></span>}<span style="white-space:pre"></span>catch (Error err) {<span style="white-space:pre"></span>ServletException ex = new NestedServletException("Handler processing failed", err);<span style="white-space:pre"></span>// Trigger after-completion for thrown exception.<span style="white-space:pre"></span>triggerAfterCompletion(mappedHandler, interceptorIndex, processedRequest, response, ex);<span style="white-space:pre"></span>throw ex;<span style="white-space:pre"></span>}<span style="white-space:pre"></span>finally {<span style="white-space:pre"></span>// Clean up any resources used by a multipart request.<span style="white-space:pre"></span>if (processedRequest != request) {<span style="white-space:pre"></span>cleanupMultipart(processedRequest);<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}<span style="white-space:pre"></span>/**<span style="white-space:pre"></span> * Build a LocaleContext for the given request, exposing the request's primary locale as current locale.<span style="white-space:pre"></span> * <p>The default implementation uses the dispatcher's LocaleResolver to obtain the current locale,<span style="white-space:pre"></span> * which might change during a request.<span style="white-space:pre"></span> * @param request current HTTP request<span style="white-space:pre"></span> * @return the corresponding LocaleContext<span style="white-space:pre"></span> */<span style="white-space:pre"></span>@Override<span style="white-space:pre"></span>protected LocaleContext buildLocaleContext(final HttpServletRequest request) {<span style="white-space:pre"></span>return new LocaleContext() {<span style="white-space:pre"></span>public Locale getLocale() {<span style="white-space:pre"></span>return localeResolver.resolveLocale(request);<span style="white-space:pre"></span>}<span style="white-space:pre"></span>@Override<span style="white-space:pre"></span>public String toString() {<span style="white-space:pre"></span>return getLocale().toString();<span style="white-space:pre"></span>}<span style="white-space:pre"></span>};<span style="white-space:pre"></span>}<span style="white-space:pre"></span>/**<span style="white-space:pre"></span> * 检查是否是请求是否是multipart(如文件上传),如果是将通过MultipartResolver解析.<span style="white-space:pre"></span> */<span style="white-space:pre"></span>protected HttpServletRequest checkMultipart(HttpServletRequest request) throws MultipartException {<span style="white-space:pre"></span>if (this.multipartResolver != null && this.multipartResolver.isMultipart(request)) {<span style="white-space:pre"></span>if (request instanceof MultipartHttpServletRequest) {<span style="white-space:pre"></span>logger.debug("Request is already a MultipartHttpServletRequest - if not in a forward, " +<span style="white-space:pre"></span>"this typically results from an additional MultipartFilter in web.xml");<span style="white-space:pre"></span>}<span style="white-space:pre"></span>else {<span style="white-space:pre"></span>return this.multipartResolver.resolveMultipart(request);<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}<span style="white-space:pre"></span>// If not returned before: return original request.<span style="white-space:pre"></span>return request;<span style="white-space:pre"></span>}<span style="white-space:pre"></span>/**<span style="white-space:pre"></span> * Clean up any resources used by the given multipart request (if any).<span style="white-space:pre"></span> * @param request current HTTP request<span style="white-space:pre"></span> * @see MultipartResolver#cleanupMultipart<span style="white-space:pre"></span> */<span style="white-space:pre"></span>protected void cleanupMultipart(HttpServletRequest request) {<span style="white-space:pre"></span>if (request instanceof MultipartHttpServletRequest) {<span style="white-space:pre"></span>this.multipartResolver.cleanupMultipart((MultipartHttpServletRequest) request);<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}<span style="white-space:pre"></span>/**<span style="white-space:pre"></span> * Return the HandlerExecutionChain for this request. Try all handler mappings in order.<span style="white-space:pre"></span> * @param request current HTTP request<span style="white-space:pre"></span> * @param cache whether to cache the HandlerExecutionChain in a request attribute<span style="white-space:pre"></span> * @return the HandlerExecutionChain, or <code>null</code> if no handler could be found<span style="white-space:pre"></span> * @deprecated as of Spring 3.0.4, in favor of {@link #getHandler(javax.servlet.http.HttpServletRequest)},<span style="white-space:pre"></span> * with this method's cache attribute now effectively getting ignored<span style="white-space:pre"></span> */<span style="white-space:pre"></span>@Deprecated<span style="white-space:pre"></span>protected HandlerExecutionChain getHandler(HttpServletRequest request, boolean cache) throws Exception {<span style="white-space:pre"></span>return getHandler(request);<span style="white-space:pre"></span>}<span style="white-space:pre"></span>/**<span style="white-space:pre"></span> * Return the HandlerExecutionChain for this request.<span style="white-space:pre"></span> * <p>Tries all handler mappings in order.<span style="white-space:pre"></span> * @param request current HTTP request<span style="white-space:pre"></span> * @return the HandlerExecutionChain, or <code>null</code> if no handler could be found<span style="white-space:pre"></span> */<span style="white-space:pre"></span>protected HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {<span style="white-space:pre"></span>for (HandlerMapping hm : this.handlerMappings) {<span style="white-space:pre"></span>if (logger.isTraceEnabled()) {<span style="white-space:pre"></span>logger.trace(<span style="white-space:pre"></span>"Testing handler map [" + hm + "] in DispatcherServlet with name '" + getServletName() + "'");<span style="white-space:pre"></span>}<span style="white-space:pre"></span>HandlerExecutionChain handler = hm.getHandler(request);<span style="white-space:pre"></span>if (handler != null) {<span style="white-space:pre"></span>return handler;<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}<span style="white-space:pre"></span>return null;<span style="white-space:pre"></span>}<span style="white-space:pre"></span>/**<span style="white-space:pre"></span> * No handler found -> set appropriate HTTP response status.<span style="white-space:pre"></span> * @param request current HTTP request<span style="white-space:pre"></span> * @param response current HTTP response<span style="white-space:pre"></span> * @throws Exception if preparing the response failed<span style="white-space:pre"></span> */<span style="white-space:pre"></span>protected void noHandlerFound(HttpServletRequest request, HttpServletResponse response) throws Exception {<span style="white-space:pre"></span>if (pageNotFoundLogger.isWarnEnabled()) {<span style="white-space:pre"></span>String requestUri = urlPathHelper.getRequestUri(request);<span style="white-space:pre"></span>pageNotFoundLogger.warn("No mapping found for HTTP request with URI [" + requestUri +<span style="white-space:pre"></span>"] in DispatcherServlet with name '" + getServletName() + "'");<span style="white-space:pre"></span>}<span style="white-space:pre"></span>response.sendError(HttpServletResponse.SC_NOT_FOUND);<span style="white-space:pre"></span>}<span style="white-space:pre"></span>/**<span style="white-space:pre"></span> * Return the HandlerAdapter for this handler object.<span style="white-space:pre"></span> * @param handler the handler object to find an adapter for<span style="white-space:pre"></span> * @throws ServletException if no HandlerAdapter can be found for the handler. This is a fatal error.<span style="white-space:pre"></span> */<span style="white-space:pre"></span>protected HandlerAdapter getHandlerAdapter(Object handler) throws ServletException {<span style="white-space:pre"></span>for (HandlerAdapter ha : this.handlerAdapters) {<span style="white-space:pre"></span>if (logger.isTraceEnabled()) {<span style="white-space:pre"></span>logger.trace("Testing handler adapter [" + ha + "]");<span style="white-space:pre"></span>}<span style="white-space:pre"></span>if (ha.supports(handler)) {<span style="white-space:pre"></span>return ha;<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}<span style="white-space:pre"></span>throw new ServletException("No adapter for handler [" + handler +<span style="white-space:pre"></span>"]: Does your handler implement a supported interface like Controller?");<span style="white-space:pre"></span>}<span style="white-space:pre"></span>/**<span style="white-space:pre"></span> * Determine an error ModelAndView via the registered HandlerExceptionResolvers.<span style="white-space:pre"></span> * @param request current HTTP request<span style="white-space:pre"></span> * @param response current HTTP response<span style="white-space:pre"></span> * @param handler the executed handler, or <code>null</code> if none chosen at the time of the exception<span style="white-space:pre"></span> * (for example, if multipart resolution failed)<span style="white-space:pre"></span> * @param ex the exception that got thrown during handler execution<span style="white-space:pre"></span> * @return a corresponding ModelAndView to forward to<span style="white-space:pre"></span> * @throws Exception if no error ModelAndView found<span style="white-space:pre"></span> */<span style="white-space:pre"></span>protected ModelAndView processHandlerException(HttpServletRequest request, HttpServletResponse response,<span style="white-space:pre"></span>Object handler, Exception ex) throws Exception {<span style="white-space:pre"></span>// Check registered HandlerExceptionResolvers...<span style="white-space:pre"></span>ModelAndView exMv = null;<span style="white-space:pre"></span>for (HandlerExceptionResolver handlerExceptionResolver : this.handlerExceptionResolvers) {<span style="white-space:pre"></span>exMv = handlerExceptionResolver.resolveException(request, response, handler, ex);<span style="white-space:pre"></span>if (exMv != null) {<span style="white-space:pre"></span>break;<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}<span style="white-space:pre"></span>if (exMv != null) {<span style="white-space:pre"></span>if (exMv.isEmpty()) {<span style="white-space:pre"></span>return null;<span style="white-space:pre"></span>}<span style="white-space:pre"></span>// We might still need view name translation for a plain error model...<span style="white-space:pre"></span>if (!exMv.hasView()) {<span style="white-space:pre"></span>exMv.setViewName(getDefaultViewName(request));<span style="white-space:pre"></span>}<span style="white-space:pre"></span>if (logger.isDebugEnabled()) {<span style="white-space:pre"></span>logger.debug("Handler execution resulted in exception - forwarding to resolved error view: " + exMv, ex);<span style="white-space:pre"></span>}<span style="white-space:pre"></span>WebUtils.exposeErrorRequestAttributes(request, ex, getServletName());<span style="white-space:pre"></span>return exMv;<span style="white-space:pre"></span>}<span style="white-space:pre"></span>throw ex;<span style="white-space:pre"></span>}<span style="white-space:pre"></span>/**<span style="white-space:pre"></span> * Render the given ModelAndView.<span style="white-space:pre"></span> * <p>This is the last stage in handling a request. It may involve resolving the view by name.<span style="white-space:pre"></span> * @param mv the ModelAndView to render<span style="white-space:pre"></span> * @param request current HTTP servlet request<span style="white-space:pre"></span> * @param response current HTTP servlet response<span style="white-space:pre"></span> * @throws ServletException if view is missing or cannot be resolved<span style="white-space:pre"></span> * @throws Exception if there's a problem rendering the view<span style="white-space:pre"></span> */<span style="white-space:pre"></span>protected void render(ModelAndView mv, HttpServletRequest request, HttpServletResponse response) throws Exception {<span style="white-space:pre"></span>// Determine locale for request and apply it to the response.<span style="white-space:pre"></span>Locale locale = this.localeResolver.resolveLocale(request);<span style="white-space:pre"></span>response.setLocale(locale);<span style="white-space:pre"></span>View view;<span style="white-space:pre"></span>if (mv.isReference()) {<span style="white-space:pre"></span>// We need to resolve the view name.<span style="white-space:pre"></span>view = resolveViewName(mv.getViewName(), mv.getModelInternal(), locale, request);<span style="white-space:pre"></span>if (view == null) {<span style="white-space:pre"></span>throw new ServletException(<span style="white-space:pre"></span>"Could not resolve view with name '" + mv.getViewName() + "' in servlet with name '" +<span style="white-space:pre"></span>getServletName() + "'");<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}<span style="white-space:pre"></span>else {<span style="white-space:pre"></span>// No need to lookup: the ModelAndView object contains the actual View object.<span style="white-space:pre"></span>view = mv.getView();<span style="white-space:pre"></span>if (view == null) {<span style="white-space:pre"></span>throw new ServletException("ModelAndView [" + mv + "] neither contains a view name nor a " +<span style="white-space:pre"></span>"View object in servlet with name '" + getServletName() + "'");<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}<span style="white-space:pre"></span>// Delegate to the View object for rendering.<span style="white-space:pre"></span>if (logger.isDebugEnabled()) {<span style="white-space:pre"></span>logger.debug("Rendering view [" + view + "] in DispatcherServlet with name '" + getServletName() + "'");<span style="white-space:pre"></span>}<span style="white-space:pre"></span>view.render(mv.getModelInternal(), request, response);<span style="white-space:pre"></span>}<span style="white-space:pre"></span>/**<span style="white-space:pre"></span> * Translate the supplied request into a default view name.<span style="white-space:pre"></span> * @param request current HTTP servlet request<span style="white-space:pre"></span> * @return the view name (or <code>null</code> if no default found)<span style="white-space:pre"></span> * @throws Exception if view name translation failed<span style="white-space:pre"></span> */<span style="white-space:pre"></span>protected String getDefaultViewName(HttpServletRequest request) throws Exception {<span style="white-space:pre"></span>return this.viewNameTranslator.getViewName(request);<span style="white-space:pre"></span>}<span style="white-space:pre"></span>/**<span style="white-space:pre"></span> * Resolve the given view name into a View object (to be rendered).<span style="white-space:pre"></span> * <p>The default implementations asks all ViewResolvers of this dispatcher.<span style="white-space:pre"></span> * Can be overridden for custom resolution strategies, potentially based on<span style="white-space:pre"></span> * specific model attributes or request parameters.<span style="white-space:pre"></span> * @param viewName the name of the view to resolve<span style="white-space:pre"></span> * @param model the model to be passed to the view<span style="white-space:pre"></span> * @param locale the current locale<span style="white-space:pre"></span> * @param request current HTTP servlet request<span style="white-space:pre"></span> * @return the View object, or <code>null</code> if none found<span style="white-space:pre"></span> * @throws Exception if the view cannot be resolved<span style="white-space:pre"></span> * (typically in case of problems creating an actual View object)<span style="white-space:pre"></span> * @see ViewResolver#resolveViewName<span style="white-space:pre"></span> */<span style="white-space:pre"></span>protected View resolveViewName(String viewName, Map<String, Object> model, Locale locale,<span style="white-space:pre"></span>HttpServletRequest request) throws Exception {<span style="white-space:pre"></span>for (ViewResolver viewResolver : this.viewResolvers) {<span style="white-space:pre"></span>View view = viewResolver.resolveViewName(viewName, locale);<span style="white-space:pre"></span>if (view != null) {<span style="white-space:pre"></span>return view;<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}<span style="white-space:pre"></span>return null;<span style="white-space:pre"></span>}<span style="white-space:pre"></span>/**<span style="white-space:pre"></span> * Trigger afterCompletion callbacks on the mapped HandlerInterceptors.<span style="white-space:pre"></span> * Will just invoke afterCompletion for all interceptors whose preHandle invocation<span style="white-space:pre"></span> * has successfully completed and returned true.<span style="white-space:pre"></span> * @param mappedHandler the mapped HandlerExecutionChain<span style="white-space:pre"></span> * @param interceptorIndex index of last interceptor that successfully completed<span style="white-space:pre"></span> * @param ex Exception thrown on handler execution, or <code>null</code> if none<span style="white-space:pre"></span> * @see HandlerInterceptor#afterCompletion<span style="white-space:pre"></span> */<span style="white-space:pre"></span>private void triggerAfterCompletion(HandlerExecutionChain mappedHandler,<span style="white-space:pre"></span>int interceptorIndex,<span style="white-space:pre"></span>HttpServletRequest request,<span style="white-space:pre"></span>HttpServletResponse response,<span style="white-space:pre"></span>Exception ex) throws Exception {<span style="white-space:pre"></span>// Apply afterCompletion methods of registered interceptors.<span style="white-space:pre"></span>if (mappedHandler != null) {<span style="white-space:pre"></span>HandlerInterceptor[] interceptors = mappedHandler.getInterceptors();<span style="white-space:pre"></span>if (interceptors != null) {<span style="white-space:pre"></span>for (int i = interceptorIndex; i >= 0; i--) {<span style="white-space:pre"></span>HandlerInterceptor interceptor = interceptors[i];<span style="white-space:pre"></span>try {<span style="white-space:pre"></span>interceptor.afterCompletion(request, response, mappedHandler.getHandler(), ex);<span style="white-space:pre"></span>}<span style="white-space:pre"></span>catch (Throwable ex2) {<span style="white-space:pre"></span>logger.error("HandlerInterceptor.afterCompletion threw exception", ex2);<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}<span style="white-space:pre"></span>/**<span style="white-space:pre"></span> * Restore the request attributes after an include.<span style="white-space:pre"></span> * @param request current HTTP request<span style="white-space:pre"></span> * @param attributesSnapshot the snapshot of the request attributes before the include<span style="white-space:pre"></span> */<span style="white-space:pre"></span>private void restoreAttributesAfterInclude(HttpServletRequest request, Map<?,?> attributesSnapshot) {<span style="white-space:pre"></span>logger.debug("Restoring snapshot of request attributes after include");<span style="white-space:pre"></span>// Need to copy into separate Collection here, to avoid side effects<span style="white-space:pre"></span>// on the Enumeration when removing attributes.<span style="white-space:pre"></span>Set<String> attrsToCheck = new HashSet<String>();<span style="white-space:pre"></span>Enumeration<?> attrNames = request.getAttributeNames();<span style="white-space:pre"></span>while (attrNames.hasMoreElements()) {<span style="white-space:pre"></span>String attrName = (String) attrNames.nextElement();<span style="white-space:pre"></span>if (this.cleanupAfterInclude || attrName.startsWith("org.springframework.web.servlet")) {<span style="white-space:pre"></span>attrsToCheck.add(attrName);<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}<span style="white-space:pre"></span>// Iterate over the attributes to check, restoring the original value<span style="white-space:pre"></span>// or removing the attribute, respectively, if appropriate.<span style="white-space:pre"></span>for (String attrName : attrsToCheck) {<span style="white-space:pre"></span>Object attrValue = attributesSnapshot.get(attrName);<span style="white-space:pre"></span>if (attrValue == null){<span style="white-space:pre"></span>if (logger.isDebugEnabled()) {<span style="white-space:pre"></span>logger.debug("Removing attribute [" + attrName + "] after include");<span style="white-space:pre"></span>}<span style="white-space:pre"></span>request.removeAttribute(attrName);<span style="white-space:pre"></span>}<span style="white-space:pre"></span>else if (attrValue != request.getAttribute(attrName)) {<span style="white-space:pre"></span>if (logger.isDebugEnabled()) {<span style="white-space:pre"></span>logger.debug("Restoring original value of attribute [" + attrName + "] after include");<span style="white-space:pre"></span>}<span style="white-space:pre"></span>request.setAttribute(attrName, attrValue);<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}}


0 0
原创粉丝点击