001/* 002 * Copyright 2002-2019 the original author or authors. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * https://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package org.springframework.web.servlet; 018 019import java.io.IOException; 020import java.util.ArrayList; 021import java.util.Arrays; 022import java.util.Collections; 023import java.util.Enumeration; 024import java.util.HashMap; 025import java.util.HashSet; 026import java.util.LinkedList; 027import java.util.List; 028import java.util.Locale; 029import java.util.Map; 030import java.util.Properties; 031import java.util.Set; 032import java.util.stream.Collectors; 033 034import javax.servlet.DispatcherType; 035import javax.servlet.ServletContext; 036import javax.servlet.ServletException; 037import javax.servlet.http.HttpServletRequest; 038import javax.servlet.http.HttpServletResponse; 039 040import org.apache.commons.logging.Log; 041import org.apache.commons.logging.LogFactory; 042 043import org.springframework.beans.factory.BeanFactoryUtils; 044import org.springframework.beans.factory.BeanInitializationException; 045import org.springframework.beans.factory.NoSuchBeanDefinitionException; 046import org.springframework.context.ApplicationContext; 047import org.springframework.context.ConfigurableApplicationContext; 048import org.springframework.context.i18n.LocaleContext; 049import org.springframework.core.annotation.AnnotationAwareOrderComparator; 050import org.springframework.core.io.ClassPathResource; 051import org.springframework.core.io.support.PropertiesLoaderUtils; 052import org.springframework.core.log.LogFormatUtils; 053import org.springframework.http.server.ServletServerHttpRequest; 054import org.springframework.lang.Nullable; 055import org.springframework.ui.context.ThemeSource; 056import org.springframework.util.ClassUtils; 057import org.springframework.util.StringUtils; 058import org.springframework.web.context.WebApplicationContext; 059import org.springframework.web.context.request.ServletWebRequest; 060import org.springframework.web.context.request.async.WebAsyncManager; 061import org.springframework.web.context.request.async.WebAsyncUtils; 062import org.springframework.web.multipart.MultipartException; 063import org.springframework.web.multipart.MultipartHttpServletRequest; 064import org.springframework.web.multipart.MultipartResolver; 065import org.springframework.web.util.NestedServletException; 066import org.springframework.web.util.WebUtils; 067 068/** 069 * Central dispatcher for HTTP request handlers/controllers, e.g. for web UI controllers 070 * or HTTP-based remote service exporters. Dispatches to registered handlers for processing 071 * a web request, providing convenient mapping and exception handling facilities. 072 * 073 * <p>This servlet is very flexible: It can be used with just about any workflow, with the 074 * installation of the appropriate adapter classes. It offers the following functionality 075 * that distinguishes it from other request-driven web MVC frameworks: 076 * 077 * <ul> 078 * <li>It is based around a JavaBeans configuration mechanism. 079 * 080 * <li>It can use any {@link HandlerMapping} implementation - pre-built or provided as part 081 * of an application - to control the routing of requests to handler objects. Default is 082 * {@link org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping} and 083 * {@link org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping}. 084 * HandlerMapping objects can be defined as beans in the servlet's application context, 085 * implementing the HandlerMapping interface, overriding the default HandlerMapping if 086 * present. HandlerMappings can be given any bean name (they are tested by type). 087 * 088 * <li>It can use any {@link HandlerAdapter}; this allows for using any handler interface. 089 * Default adapters are {@link org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter}, 090 * {@link org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter}, for Spring's 091 * {@link org.springframework.web.HttpRequestHandler} and 092 * {@link org.springframework.web.servlet.mvc.Controller} interfaces, respectively. A default 093 * {@link org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter} 094 * will be registered as well. HandlerAdapter objects can be added as beans in the 095 * application context, overriding the default HandlerAdapters. Like HandlerMappings, 096 * HandlerAdapters can be given any bean name (they are tested by type). 097 * 098 * <li>The dispatcher's exception resolution strategy can be specified via a 099 * {@link HandlerExceptionResolver}, for example mapping certain exceptions to error pages. 100 * Default are 101 * {@link org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver}, 102 * {@link org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver}, and 103 * {@link org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver}. 104 * These HandlerExceptionResolvers can be overridden through the application context. 105 * HandlerExceptionResolver can be given any bean name (they are tested by type). 106 * 107 * <li>Its view resolution strategy can be specified via a {@link ViewResolver} 108 * implementation, resolving symbolic view names into View objects. Default is 109 * {@link org.springframework.web.servlet.view.InternalResourceViewResolver}. 110 * ViewResolver objects can be added as beans in the application context, overriding the 111 * default ViewResolver. ViewResolvers can be given any bean name (they are tested by type). 112 * 113 * <li>If a {@link View} or view name is not supplied by the user, then the configured 114 * {@link RequestToViewNameTranslator} will translate the current request into a view name. 115 * The corresponding bean name is "viewNameTranslator"; the default is 116 * {@link org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator}. 117 * 118 * <li>The dispatcher's strategy for resolving multipart requests is determined by a 119 * {@link org.springframework.web.multipart.MultipartResolver} implementation. 120 * Implementations for Apache Commons FileUpload and Servlet 3 are included; the typical 121 * choice is {@link org.springframework.web.multipart.commons.CommonsMultipartResolver}. 122 * The MultipartResolver bean name is "multipartResolver"; default is none. 123 * 124 * <li>Its locale resolution strategy is determined by a {@link LocaleResolver}. 125 * Out-of-the-box implementations work via HTTP accept header, cookie, or session. 126 * The LocaleResolver bean name is "localeResolver"; default is 127 * {@link org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver}. 128 * 129 * <li>Its theme resolution strategy is determined by a {@link ThemeResolver}. 130 * Implementations for a fixed theme and for cookie and session storage are included. 131 * The ThemeResolver bean name is "themeResolver"; default is 132 * {@link org.springframework.web.servlet.theme.FixedThemeResolver}. 133 * </ul> 134 * 135 * <p><b>NOTE: The {@code @RequestMapping} annotation will only be processed if a 136 * corresponding {@code HandlerMapping} (for type-level annotations) and/or 137 * {@code HandlerAdapter} (for method-level annotations) is present in the dispatcher.</b> 138 * This is the case by default. However, if you are defining custom {@code HandlerMappings} 139 * or {@code HandlerAdapters}, then you need to make sure that a corresponding custom 140 * {@code RequestMappingHandlerMapping} and/or {@code RequestMappingHandlerAdapter} 141 * is defined as well - provided that you intend to use {@code @RequestMapping}. 142 * 143 * <p><b>A web application can define any number of DispatcherServlets.</b> 144 * Each servlet will operate in its own namespace, loading its own application context 145 * with mappings, handlers, etc. Only the root application context as loaded by 146 * {@link org.springframework.web.context.ContextLoaderListener}, if any, will be shared. 147 * 148 * <p>As of Spring 3.1, {@code DispatcherServlet} may now be injected with a web 149 * application context, rather than creating its own internally. This is useful in Servlet 150 * 3.0+ environments, which support programmatic registration of servlet instances. 151 * See the {@link #DispatcherServlet(WebApplicationContext)} javadoc for details. 152 * 153 * @author Rod Johnson 154 * @author Juergen Hoeller 155 * @author Rob Harrop 156 * @author Chris Beams 157 * @author Rossen Stoyanchev 158 * @see org.springframework.web.HttpRequestHandler 159 * @see org.springframework.web.servlet.mvc.Controller 160 * @see org.springframework.web.context.ContextLoaderListener 161 */ 162@SuppressWarnings("serial") 163public class DispatcherServlet extends FrameworkServlet { 164 165 /** Well-known name for the MultipartResolver object in the bean factory for this namespace. */ 166 public static final String MULTIPART_RESOLVER_BEAN_NAME = "multipartResolver"; 167 168 /** Well-known name for the LocaleResolver object in the bean factory for this namespace. */ 169 public static final String LOCALE_RESOLVER_BEAN_NAME = "localeResolver"; 170 171 /** Well-known name for the ThemeResolver object in the bean factory for this namespace. */ 172 public static final String THEME_RESOLVER_BEAN_NAME = "themeResolver"; 173 174 /** 175 * Well-known name for the HandlerMapping object in the bean factory for this namespace. 176 * Only used when "detectAllHandlerMappings" is turned off. 177 * @see #setDetectAllHandlerMappings 178 */ 179 public static final String HANDLER_MAPPING_BEAN_NAME = "handlerMapping"; 180 181 /** 182 * Well-known name for the HandlerAdapter object in the bean factory for this namespace. 183 * Only used when "detectAllHandlerAdapters" is turned off. 184 * @see #setDetectAllHandlerAdapters 185 */ 186 public static final String HANDLER_ADAPTER_BEAN_NAME = "handlerAdapter"; 187 188 /** 189 * Well-known name for the HandlerExceptionResolver object in the bean factory for this namespace. 190 * Only used when "detectAllHandlerExceptionResolvers" is turned off. 191 * @see #setDetectAllHandlerExceptionResolvers 192 */ 193 public static final String HANDLER_EXCEPTION_RESOLVER_BEAN_NAME = "handlerExceptionResolver"; 194 195 /** 196 * Well-known name for the RequestToViewNameTranslator object in the bean factory for this namespace. 197 */ 198 public static final String REQUEST_TO_VIEW_NAME_TRANSLATOR_BEAN_NAME = "viewNameTranslator"; 199 200 /** 201 * Well-known name for the ViewResolver object in the bean factory for this namespace. 202 * Only used when "detectAllViewResolvers" is turned off. 203 * @see #setDetectAllViewResolvers 204 */ 205 public static final String VIEW_RESOLVER_BEAN_NAME = "viewResolver"; 206 207 /** 208 * Well-known name for the FlashMapManager object in the bean factory for this namespace. 209 */ 210 public static final String FLASH_MAP_MANAGER_BEAN_NAME = "flashMapManager"; 211 212 /** 213 * Request attribute to hold the current web application context. 214 * Otherwise only the global web app context is obtainable by tags etc. 215 * @see org.springframework.web.servlet.support.RequestContextUtils#findWebApplicationContext 216 */ 217 public static final String WEB_APPLICATION_CONTEXT_ATTRIBUTE = DispatcherServlet.class.getName() + ".CONTEXT"; 218 219 /** 220 * Request attribute to hold the current LocaleResolver, retrievable by views. 221 * @see org.springframework.web.servlet.support.RequestContextUtils#getLocaleResolver 222 */ 223 public static final String LOCALE_RESOLVER_ATTRIBUTE = DispatcherServlet.class.getName() + ".LOCALE_RESOLVER"; 224 225 /** 226 * Request attribute to hold the current ThemeResolver, retrievable by views. 227 * @see org.springframework.web.servlet.support.RequestContextUtils#getThemeResolver 228 */ 229 public static final String THEME_RESOLVER_ATTRIBUTE = DispatcherServlet.class.getName() + ".THEME_RESOLVER"; 230 231 /** 232 * Request attribute to hold the current ThemeSource, retrievable by views. 233 * @see org.springframework.web.servlet.support.RequestContextUtils#getThemeSource 234 */ 235 public static final String THEME_SOURCE_ATTRIBUTE = DispatcherServlet.class.getName() + ".THEME_SOURCE"; 236 237 /** 238 * Name of request attribute that holds a read-only {@code Map<String,?>} 239 * with "input" flash attributes saved by a previous request, if any. 240 * @see org.springframework.web.servlet.support.RequestContextUtils#getInputFlashMap(HttpServletRequest) 241 */ 242 public static final String INPUT_FLASH_MAP_ATTRIBUTE = DispatcherServlet.class.getName() + ".INPUT_FLASH_MAP"; 243 244 /** 245 * Name of request attribute that holds the "output" {@link FlashMap} with 246 * attributes to save for a subsequent request. 247 * @see org.springframework.web.servlet.support.RequestContextUtils#getOutputFlashMap(HttpServletRequest) 248 */ 249 public static final String OUTPUT_FLASH_MAP_ATTRIBUTE = DispatcherServlet.class.getName() + ".OUTPUT_FLASH_MAP"; 250 251 /** 252 * Name of request attribute that holds the {@link FlashMapManager}. 253 * @see org.springframework.web.servlet.support.RequestContextUtils#getFlashMapManager(HttpServletRequest) 254 */ 255 public static final String FLASH_MAP_MANAGER_ATTRIBUTE = DispatcherServlet.class.getName() + ".FLASH_MAP_MANAGER"; 256 257 /** 258 * Name of request attribute that exposes an Exception resolved with a 259 * {@link HandlerExceptionResolver} but where no view was rendered 260 * (e.g. setting the status code). 261 */ 262 public static final String EXCEPTION_ATTRIBUTE = DispatcherServlet.class.getName() + ".EXCEPTION"; 263 264 /** Log category to use when no mapped handler is found for a request. */ 265 public static final String PAGE_NOT_FOUND_LOG_CATEGORY = "org.springframework.web.servlet.PageNotFound"; 266 267 /** 268 * Name of the class path resource (relative to the DispatcherServlet class) 269 * that defines DispatcherServlet's default strategy names. 270 */ 271 private static final String DEFAULT_STRATEGIES_PATH = "DispatcherServlet.properties"; 272 273 /** 274 * Common prefix that DispatcherServlet's default strategy attributes start with. 275 */ 276 private static final String DEFAULT_STRATEGIES_PREFIX = "org.springframework.web.servlet"; 277 278 /** Additional logger to use when no mapped handler is found for a request. */ 279 protected static final Log pageNotFoundLogger = LogFactory.getLog(PAGE_NOT_FOUND_LOG_CATEGORY); 280 281 private static final Properties defaultStrategies; 282 283 static { 284 // Load default strategy implementations from properties file. 285 // This is currently strictly internal and not meant to be customized 286 // by application developers. 287 try { 288 ClassPathResource resource = new ClassPathResource(DEFAULT_STRATEGIES_PATH, DispatcherServlet.class); 289 defaultStrategies = PropertiesLoaderUtils.loadProperties(resource); 290 } 291 catch (IOException ex) { 292 throw new IllegalStateException("Could not load '" + DEFAULT_STRATEGIES_PATH + "': " + ex.getMessage()); 293 } 294 } 295 296 /** Detect all HandlerMappings or just expect "handlerMapping" bean?. */ 297 private boolean detectAllHandlerMappings = true; 298 299 /** Detect all HandlerAdapters or just expect "handlerAdapter" bean?. */ 300 private boolean detectAllHandlerAdapters = true; 301 302 /** Detect all HandlerExceptionResolvers or just expect "handlerExceptionResolver" bean?. */ 303 private boolean detectAllHandlerExceptionResolvers = true; 304 305 /** Detect all ViewResolvers or just expect "viewResolver" bean?. */ 306 private boolean detectAllViewResolvers = true; 307 308 /** Throw a NoHandlerFoundException if no Handler was found to process this request? *.*/ 309 private boolean throwExceptionIfNoHandlerFound = false; 310 311 /** Perform cleanup of request attributes after include request?. */ 312 private boolean cleanupAfterInclude = true; 313 314 /** MultipartResolver used by this servlet. */ 315 @Nullable 316 private MultipartResolver multipartResolver; 317 318 /** LocaleResolver used by this servlet. */ 319 @Nullable 320 private LocaleResolver localeResolver; 321 322 /** ThemeResolver used by this servlet. */ 323 @Nullable 324 private ThemeResolver themeResolver; 325 326 /** List of HandlerMappings used by this servlet. */ 327 @Nullable 328 private List<HandlerMapping> handlerMappings; 329 330 /** List of HandlerAdapters used by this servlet. */ 331 @Nullable 332 private List<HandlerAdapter> handlerAdapters; 333 334 /** List of HandlerExceptionResolvers used by this servlet. */ 335 @Nullable 336 private List<HandlerExceptionResolver> handlerExceptionResolvers; 337 338 /** RequestToViewNameTranslator used by this servlet. */ 339 @Nullable 340 private RequestToViewNameTranslator viewNameTranslator; 341 342 /** FlashMapManager used by this servlet. */ 343 @Nullable 344 private FlashMapManager flashMapManager; 345 346 /** List of ViewResolvers used by this servlet. */ 347 @Nullable 348 private List<ViewResolver> viewResolvers; 349 350 351 /** 352 * Create a new {@code DispatcherServlet} that will create its own internal web 353 * application context based on defaults and values provided through servlet 354 * init-params. Typically used in Servlet 2.5 or earlier environments, where the only 355 * option for servlet registration is through {@code web.xml} which requires the use 356 * of a no-arg constructor. 357 * <p>Calling {@link #setContextConfigLocation} (init-param 'contextConfigLocation') 358 * will dictate which XML files will be loaded by the 359 * {@linkplain #DEFAULT_CONTEXT_CLASS default XmlWebApplicationContext} 360 * <p>Calling {@link #setContextClass} (init-param 'contextClass') overrides the 361 * default {@code XmlWebApplicationContext} and allows for specifying an alternative class, 362 * such as {@code AnnotationConfigWebApplicationContext}. 363 * <p>Calling {@link #setContextInitializerClasses} (init-param 'contextInitializerClasses') 364 * indicates which {@code ApplicationContextInitializer} classes should be used to 365 * further configure the internal application context prior to refresh(). 366 * @see #DispatcherServlet(WebApplicationContext) 367 */ 368 public DispatcherServlet() { 369 super(); 370 setDispatchOptionsRequest(true); 371 } 372 373 /** 374 * Create a new {@code DispatcherServlet} with the given web application context. This 375 * constructor is useful in Servlet 3.0+ environments where instance-based registration 376 * of servlets is possible through the {@link ServletContext#addServlet} API. 377 * <p>Using this constructor indicates that the following properties / init-params 378 * will be ignored: 379 * <ul> 380 * <li>{@link #setContextClass(Class)} / 'contextClass'</li> 381 * <li>{@link #setContextConfigLocation(String)} / 'contextConfigLocation'</li> 382 * <li>{@link #setContextAttribute(String)} / 'contextAttribute'</li> 383 * <li>{@link #setNamespace(String)} / 'namespace'</li> 384 * </ul> 385 * <p>The given web application context may or may not yet be {@linkplain 386 * ConfigurableApplicationContext#refresh() refreshed}. If it has <strong>not</strong> 387 * already been refreshed (the recommended approach), then the following will occur: 388 * <ul> 389 * <li>If the given context does not already have a {@linkplain 390 * ConfigurableApplicationContext#setParent parent}, the root application context 391 * will be set as the parent.</li> 392 * <li>If the given context has not already been assigned an {@linkplain 393 * ConfigurableApplicationContext#setId id}, one will be assigned to it</li> 394 * <li>{@code ServletContext} and {@code ServletConfig} objects will be delegated to 395 * the application context</li> 396 * <li>{@link #postProcessWebApplicationContext} will be called</li> 397 * <li>Any {@code ApplicationContextInitializer}s specified through the 398 * "contextInitializerClasses" init-param or through the {@link 399 * #setContextInitializers} property will be applied.</li> 400 * <li>{@link ConfigurableApplicationContext#refresh refresh()} will be called if the 401 * context implements {@link ConfigurableApplicationContext}</li> 402 * </ul> 403 * If the context has already been refreshed, none of the above will occur, under the 404 * assumption that the user has performed these actions (or not) per their specific 405 * needs. 406 * <p>See {@link org.springframework.web.WebApplicationInitializer} for usage examples. 407 * @param webApplicationContext the context to use 408 * @see #initWebApplicationContext 409 * @see #configureAndRefreshWebApplicationContext 410 * @see org.springframework.web.WebApplicationInitializer 411 */ 412 public DispatcherServlet(WebApplicationContext webApplicationContext) { 413 super(webApplicationContext); 414 setDispatchOptionsRequest(true); 415 } 416 417 418 /** 419 * Set whether to detect all HandlerMapping beans in this servlet's context. Otherwise, 420 * just a single bean with name "handlerMapping" will be expected. 421 * <p>Default is "true". Turn this off if you want this servlet to use a single 422 * HandlerMapping, despite multiple HandlerMapping beans being defined in the context. 423 */ 424 public void setDetectAllHandlerMappings(boolean detectAllHandlerMappings) { 425 this.detectAllHandlerMappings = detectAllHandlerMappings; 426 } 427 428 /** 429 * Set whether to detect all HandlerAdapter beans in this servlet's context. Otherwise, 430 * just a single bean with name "handlerAdapter" will be expected. 431 * <p>Default is "true". Turn this off if you want this servlet to use a single 432 * HandlerAdapter, despite multiple HandlerAdapter beans being defined in the context. 433 */ 434 public void setDetectAllHandlerAdapters(boolean detectAllHandlerAdapters) { 435 this.detectAllHandlerAdapters = detectAllHandlerAdapters; 436 } 437 438 /** 439 * Set whether to detect all HandlerExceptionResolver beans in this servlet's context. Otherwise, 440 * just a single bean with name "handlerExceptionResolver" will be expected. 441 * <p>Default is "true". Turn this off if you want this servlet to use a single 442 * HandlerExceptionResolver, despite multiple HandlerExceptionResolver beans being defined in the context. 443 */ 444 public void setDetectAllHandlerExceptionResolvers(boolean detectAllHandlerExceptionResolvers) { 445 this.detectAllHandlerExceptionResolvers = detectAllHandlerExceptionResolvers; 446 } 447 448 /** 449 * Set whether to detect all ViewResolver beans in this servlet's context. Otherwise, 450 * just a single bean with name "viewResolver" will be expected. 451 * <p>Default is "true". Turn this off if you want this servlet to use a single 452 * ViewResolver, despite multiple ViewResolver beans being defined in the context. 453 */ 454 public void setDetectAllViewResolvers(boolean detectAllViewResolvers) { 455 this.detectAllViewResolvers = detectAllViewResolvers; 456 } 457 458 /** 459 * Set whether to throw a NoHandlerFoundException when no Handler was found for this request. 460 * This exception can then be caught with a HandlerExceptionResolver or an 461 * {@code @ExceptionHandler} controller method. 462 * <p>Note that if {@link org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler} 463 * is used, then requests will always be forwarded to the default servlet and a 464 * NoHandlerFoundException would never be thrown in that case. 465 * <p>Default is "false", meaning the DispatcherServlet sends a NOT_FOUND error through the 466 * Servlet response. 467 * @since 4.0 468 */ 469 public void setThrowExceptionIfNoHandlerFound(boolean throwExceptionIfNoHandlerFound) { 470 this.throwExceptionIfNoHandlerFound = throwExceptionIfNoHandlerFound; 471 } 472 473 /** 474 * Set whether to perform cleanup of request attributes after an include request, that is, 475 * whether to reset the original state of all request attributes after the DispatcherServlet 476 * has processed within an include request. Otherwise, just the DispatcherServlet's own 477 * request attributes will be reset, but not model attributes for JSPs or special attributes 478 * set by views (for example, JSTL's). 479 * <p>Default is "true", which is strongly recommended. Views should not rely on request attributes 480 * having been set by (dynamic) includes. This allows JSP views rendered by an included controller 481 * to use any model attributes, even with the same names as in the main JSP, without causing side 482 * effects. Only turn this off for special needs, for example to deliberately allow main JSPs to 483 * access attributes from JSP views rendered by an included controller. 484 */ 485 public void setCleanupAfterInclude(boolean cleanupAfterInclude) { 486 this.cleanupAfterInclude = cleanupAfterInclude; 487 } 488 489 490 /** 491 * This implementation calls {@link #initStrategies}. 492 */ 493 @Override 494 protected void onRefresh(ApplicationContext context) { 495 initStrategies(context); 496 } 497 498 /** 499 * Initialize the strategy objects that this servlet uses. 500 * <p>May be overridden in subclasses in order to initialize further strategy objects. 501 */ 502 protected void initStrategies(ApplicationContext context) { 503 initMultipartResolver(context); 504 initLocaleResolver(context); 505 initThemeResolver(context); 506 initHandlerMappings(context); 507 initHandlerAdapters(context); 508 initHandlerExceptionResolvers(context); 509 initRequestToViewNameTranslator(context); 510 initViewResolvers(context); 511 initFlashMapManager(context); 512 } 513 514 /** 515 * Initialize the MultipartResolver used by this class. 516 * <p>If no bean is defined with the given name in the BeanFactory for this namespace, 517 * no multipart handling is provided. 518 */ 519 private void initMultipartResolver(ApplicationContext context) { 520 try { 521 this.multipartResolver = context.getBean(MULTIPART_RESOLVER_BEAN_NAME, MultipartResolver.class); 522 if (logger.isTraceEnabled()) { 523 logger.trace("Detected " + this.multipartResolver); 524 } 525 else if (logger.isDebugEnabled()) { 526 logger.debug("Detected " + this.multipartResolver.getClass().getSimpleName()); 527 } 528 } 529 catch (NoSuchBeanDefinitionException ex) { 530 // Default is no multipart resolver. 531 this.multipartResolver = null; 532 if (logger.isTraceEnabled()) { 533 logger.trace("No MultipartResolver '" + MULTIPART_RESOLVER_BEAN_NAME + "' declared"); 534 } 535 } 536 } 537 538 /** 539 * Initialize the LocaleResolver used by this class. 540 * <p>If no bean is defined with the given name in the BeanFactory for this namespace, 541 * we default to AcceptHeaderLocaleResolver. 542 */ 543 private void initLocaleResolver(ApplicationContext context) { 544 try { 545 this.localeResolver = context.getBean(LOCALE_RESOLVER_BEAN_NAME, LocaleResolver.class); 546 if (logger.isTraceEnabled()) { 547 logger.trace("Detected " + this.localeResolver); 548 } 549 else if (logger.isDebugEnabled()) { 550 logger.debug("Detected " + this.localeResolver.getClass().getSimpleName()); 551 } 552 } 553 catch (NoSuchBeanDefinitionException ex) { 554 // We need to use the default. 555 this.localeResolver = getDefaultStrategy(context, LocaleResolver.class); 556 if (logger.isTraceEnabled()) { 557 logger.trace("No LocaleResolver '" + LOCALE_RESOLVER_BEAN_NAME + 558 "': using default [" + this.localeResolver.getClass().getSimpleName() + "]"); 559 } 560 } 561 } 562 563 /** 564 * Initialize the ThemeResolver used by this class. 565 * <p>If no bean is defined with the given name in the BeanFactory for this namespace, 566 * we default to a FixedThemeResolver. 567 */ 568 private void initThemeResolver(ApplicationContext context) { 569 try { 570 this.themeResolver = context.getBean(THEME_RESOLVER_BEAN_NAME, ThemeResolver.class); 571 if (logger.isTraceEnabled()) { 572 logger.trace("Detected " + this.themeResolver); 573 } 574 else if (logger.isDebugEnabled()) { 575 logger.debug("Detected " + this.themeResolver.getClass().getSimpleName()); 576 } 577 } 578 catch (NoSuchBeanDefinitionException ex) { 579 // We need to use the default. 580 this.themeResolver = getDefaultStrategy(context, ThemeResolver.class); 581 if (logger.isTraceEnabled()) { 582 logger.trace("No ThemeResolver '" + THEME_RESOLVER_BEAN_NAME + 583 "': using default [" + this.themeResolver.getClass().getSimpleName() + "]"); 584 } 585 } 586 } 587 588 /** 589 * Initialize the HandlerMappings used by this class. 590 * <p>If no HandlerMapping beans are defined in the BeanFactory for this namespace, 591 * we default to BeanNameUrlHandlerMapping. 592 */ 593 private void initHandlerMappings(ApplicationContext context) { 594 this.handlerMappings = null; 595 596 if (this.detectAllHandlerMappings) { 597 // Find all HandlerMappings in the ApplicationContext, including ancestor contexts. 598 Map<String, HandlerMapping> matchingBeans = 599 BeanFactoryUtils.beansOfTypeIncludingAncestors(context, HandlerMapping.class, true, false); 600 if (!matchingBeans.isEmpty()) { 601 this.handlerMappings = new ArrayList<>(matchingBeans.values()); 602 // We keep HandlerMappings in sorted order. 603 AnnotationAwareOrderComparator.sort(this.handlerMappings); 604 } 605 } 606 else { 607 try { 608 HandlerMapping hm = context.getBean(HANDLER_MAPPING_BEAN_NAME, HandlerMapping.class); 609 this.handlerMappings = Collections.singletonList(hm); 610 } 611 catch (NoSuchBeanDefinitionException ex) { 612 // Ignore, we'll add a default HandlerMapping later. 613 } 614 } 615 616 // Ensure we have at least one HandlerMapping, by registering 617 // a default HandlerMapping if no other mappings are found. 618 if (this.handlerMappings == null) { 619 this.handlerMappings = getDefaultStrategies(context, HandlerMapping.class); 620 if (logger.isTraceEnabled()) { 621 logger.trace("No HandlerMappings declared for servlet '" + getServletName() + 622 "': using default strategies from DispatcherServlet.properties"); 623 } 624 } 625 } 626 627 /** 628 * Initialize the HandlerAdapters used by this class. 629 * <p>If no HandlerAdapter beans are defined in the BeanFactory for this namespace, 630 * we default to SimpleControllerHandlerAdapter. 631 */ 632 private void initHandlerAdapters(ApplicationContext context) { 633 this.handlerAdapters = null; 634 635 if (this.detectAllHandlerAdapters) { 636 // Find all HandlerAdapters in the ApplicationContext, including ancestor contexts. 637 Map<String, HandlerAdapter> matchingBeans = 638 BeanFactoryUtils.beansOfTypeIncludingAncestors(context, HandlerAdapter.class, true, false); 639 if (!matchingBeans.isEmpty()) { 640 this.handlerAdapters = new ArrayList<>(matchingBeans.values()); 641 // We keep HandlerAdapters in sorted order. 642 AnnotationAwareOrderComparator.sort(this.handlerAdapters); 643 } 644 } 645 else { 646 try { 647 HandlerAdapter ha = context.getBean(HANDLER_ADAPTER_BEAN_NAME, HandlerAdapter.class); 648 this.handlerAdapters = Collections.singletonList(ha); 649 } 650 catch (NoSuchBeanDefinitionException ex) { 651 // Ignore, we'll add a default HandlerAdapter later. 652 } 653 } 654 655 // Ensure we have at least some HandlerAdapters, by registering 656 // default HandlerAdapters if no other adapters are found. 657 if (this.handlerAdapters == null) { 658 this.handlerAdapters = getDefaultStrategies(context, HandlerAdapter.class); 659 if (logger.isTraceEnabled()) { 660 logger.trace("No HandlerAdapters declared for servlet '" + getServletName() + 661 "': using default strategies from DispatcherServlet.properties"); 662 } 663 } 664 } 665 666 /** 667 * Initialize the HandlerExceptionResolver used by this class. 668 * <p>If no bean is defined with the given name in the BeanFactory for this namespace, 669 * we default to no exception resolver. 670 */ 671 private void initHandlerExceptionResolvers(ApplicationContext context) { 672 this.handlerExceptionResolvers = null; 673 674 if (this.detectAllHandlerExceptionResolvers) { 675 // Find all HandlerExceptionResolvers in the ApplicationContext, including ancestor contexts. 676 Map<String, HandlerExceptionResolver> matchingBeans = BeanFactoryUtils 677 .beansOfTypeIncludingAncestors(context, HandlerExceptionResolver.class, true, false); 678 if (!matchingBeans.isEmpty()) { 679 this.handlerExceptionResolvers = new ArrayList<>(matchingBeans.values()); 680 // We keep HandlerExceptionResolvers in sorted order. 681 AnnotationAwareOrderComparator.sort(this.handlerExceptionResolvers); 682 } 683 } 684 else { 685 try { 686 HandlerExceptionResolver her = 687 context.getBean(HANDLER_EXCEPTION_RESOLVER_BEAN_NAME, HandlerExceptionResolver.class); 688 this.handlerExceptionResolvers = Collections.singletonList(her); 689 } 690 catch (NoSuchBeanDefinitionException ex) { 691 // Ignore, no HandlerExceptionResolver is fine too. 692 } 693 } 694 695 // Ensure we have at least some HandlerExceptionResolvers, by registering 696 // default HandlerExceptionResolvers if no other resolvers are found. 697 if (this.handlerExceptionResolvers == null) { 698 this.handlerExceptionResolvers = getDefaultStrategies(context, HandlerExceptionResolver.class); 699 if (logger.isTraceEnabled()) { 700 logger.trace("No HandlerExceptionResolvers declared in servlet '" + getServletName() + 701 "': using default strategies from DispatcherServlet.properties"); 702 } 703 } 704 } 705 706 /** 707 * Initialize the RequestToViewNameTranslator used by this servlet instance. 708 * <p>If no implementation is configured then we default to DefaultRequestToViewNameTranslator. 709 */ 710 private void initRequestToViewNameTranslator(ApplicationContext context) { 711 try { 712 this.viewNameTranslator = 713 context.getBean(REQUEST_TO_VIEW_NAME_TRANSLATOR_BEAN_NAME, RequestToViewNameTranslator.class); 714 if (logger.isTraceEnabled()) { 715 logger.trace("Detected " + this.viewNameTranslator.getClass().getSimpleName()); 716 } 717 else if (logger.isDebugEnabled()) { 718 logger.debug("Detected " + this.viewNameTranslator); 719 } 720 } 721 catch (NoSuchBeanDefinitionException ex) { 722 // We need to use the default. 723 this.viewNameTranslator = getDefaultStrategy(context, RequestToViewNameTranslator.class); 724 if (logger.isTraceEnabled()) { 725 logger.trace("No RequestToViewNameTranslator '" + REQUEST_TO_VIEW_NAME_TRANSLATOR_BEAN_NAME + 726 "': using default [" + this.viewNameTranslator.getClass().getSimpleName() + "]"); 727 } 728 } 729 } 730 731 /** 732 * Initialize the ViewResolvers used by this class. 733 * <p>If no ViewResolver beans are defined in the BeanFactory for this 734 * namespace, we default to InternalResourceViewResolver. 735 */ 736 private void initViewResolvers(ApplicationContext context) { 737 this.viewResolvers = null; 738 739 if (this.detectAllViewResolvers) { 740 // Find all ViewResolvers in the ApplicationContext, including ancestor contexts. 741 Map<String, ViewResolver> matchingBeans = 742 BeanFactoryUtils.beansOfTypeIncludingAncestors(context, ViewResolver.class, true, false); 743 if (!matchingBeans.isEmpty()) { 744 this.viewResolvers = new ArrayList<>(matchingBeans.values()); 745 // We keep ViewResolvers in sorted order. 746 AnnotationAwareOrderComparator.sort(this.viewResolvers); 747 } 748 } 749 else { 750 try { 751 ViewResolver vr = context.getBean(VIEW_RESOLVER_BEAN_NAME, ViewResolver.class); 752 this.viewResolvers = Collections.singletonList(vr); 753 } 754 catch (NoSuchBeanDefinitionException ex) { 755 // Ignore, we'll add a default ViewResolver later. 756 } 757 } 758 759 // Ensure we have at least one ViewResolver, by registering 760 // a default ViewResolver if no other resolvers are found. 761 if (this.viewResolvers == null) { 762 this.viewResolvers = getDefaultStrategies(context, ViewResolver.class); 763 if (logger.isTraceEnabled()) { 764 logger.trace("No ViewResolvers declared for servlet '" + getServletName() + 765 "': using default strategies from DispatcherServlet.properties"); 766 } 767 } 768 } 769 770 /** 771 * Initialize the {@link FlashMapManager} used by this servlet instance. 772 * <p>If no implementation is configured then we default to 773 * {@code org.springframework.web.servlet.support.DefaultFlashMapManager}. 774 */ 775 private void initFlashMapManager(ApplicationContext context) { 776 try { 777 this.flashMapManager = context.getBean(FLASH_MAP_MANAGER_BEAN_NAME, FlashMapManager.class); 778 if (logger.isTraceEnabled()) { 779 logger.trace("Detected " + this.flashMapManager.getClass().getSimpleName()); 780 } 781 else if (logger.isDebugEnabled()) { 782 logger.debug("Detected " + this.flashMapManager); 783 } 784 } 785 catch (NoSuchBeanDefinitionException ex) { 786 // We need to use the default. 787 this.flashMapManager = getDefaultStrategy(context, FlashMapManager.class); 788 if (logger.isTraceEnabled()) { 789 logger.trace("No FlashMapManager '" + FLASH_MAP_MANAGER_BEAN_NAME + 790 "': using default [" + this.flashMapManager.getClass().getSimpleName() + "]"); 791 } 792 } 793 } 794 795 /** 796 * Return this servlet's ThemeSource, if any; else return {@code null}. 797 * <p>Default is to return the WebApplicationContext as ThemeSource, 798 * provided that it implements the ThemeSource interface. 799 * @return the ThemeSource, if any 800 * @see #getWebApplicationContext() 801 */ 802 @Nullable 803 public final ThemeSource getThemeSource() { 804 return (getWebApplicationContext() instanceof ThemeSource ? (ThemeSource) getWebApplicationContext() : null); 805 } 806 807 /** 808 * Obtain this servlet's MultipartResolver, if any. 809 * @return the MultipartResolver used by this servlet, or {@code null} if none 810 * (indicating that no multipart support is available) 811 */ 812 @Nullable 813 public final MultipartResolver getMultipartResolver() { 814 return this.multipartResolver; 815 } 816 817 /** 818 * Return the configured {@link HandlerMapping} beans that were detected by 819 * type in the {@link WebApplicationContext} or initialized based on the 820 * default set of strategies from {@literal DispatcherServlet.properties}. 821 * <p><strong>Note:</strong> This method may return {@code null} if invoked 822 * prior to {@link #onRefresh(ApplicationContext)}. 823 * @return an immutable list with the configured mappings, or {@code null} 824 * if not initialized yet 825 * @since 5.0 826 */ 827 @Nullable 828 public final List<HandlerMapping> getHandlerMappings() { 829 return (this.handlerMappings != null ? Collections.unmodifiableList(this.handlerMappings) : null); 830 } 831 832 /** 833 * Return the default strategy object for the given strategy interface. 834 * <p>The default implementation delegates to {@link #getDefaultStrategies}, 835 * expecting a single object in the list. 836 * @param context the current WebApplicationContext 837 * @param strategyInterface the strategy interface 838 * @return the corresponding strategy object 839 * @see #getDefaultStrategies 840 */ 841 protected <T> T getDefaultStrategy(ApplicationContext context, Class<T> strategyInterface) { 842 List<T> strategies = getDefaultStrategies(context, strategyInterface); 843 if (strategies.size() != 1) { 844 throw new BeanInitializationException( 845 "DispatcherServlet needs exactly 1 strategy for interface [" + strategyInterface.getName() + "]"); 846 } 847 return strategies.get(0); 848 } 849 850 /** 851 * Create a List of default strategy objects for the given strategy interface. 852 * <p>The default implementation uses the "DispatcherServlet.properties" file (in the same 853 * package as the DispatcherServlet class) to determine the class names. It instantiates 854 * the strategy objects through the context's BeanFactory. 855 * @param context the current WebApplicationContext 856 * @param strategyInterface the strategy interface 857 * @return the List of corresponding strategy objects 858 */ 859 @SuppressWarnings("unchecked") 860 protected <T> List<T> getDefaultStrategies(ApplicationContext context, Class<T> strategyInterface) { 861 String key = strategyInterface.getName(); 862 String value = defaultStrategies.getProperty(key); 863 if (value != null) { 864 String[] classNames = StringUtils.commaDelimitedListToStringArray(value); 865 List<T> strategies = new ArrayList<>(classNames.length); 866 for (String className : classNames) { 867 try { 868 Class<?> clazz = ClassUtils.forName(className, DispatcherServlet.class.getClassLoader()); 869 Object strategy = createDefaultStrategy(context, clazz); 870 strategies.add((T) strategy); 871 } 872 catch (ClassNotFoundException ex) { 873 throw new BeanInitializationException( 874 "Could not find DispatcherServlet's default strategy class [" + className + 875 "] for interface [" + key + "]", ex); 876 } 877 catch (LinkageError err) { 878 throw new BeanInitializationException( 879 "Unresolvable class definition for DispatcherServlet's default strategy class [" + 880 className + "] for interface [" + key + "]", err); 881 } 882 } 883 return strategies; 884 } 885 else { 886 return new LinkedList<>(); 887 } 888 } 889 890 /** 891 * Create a default strategy. 892 * <p>The default implementation uses 893 * {@link org.springframework.beans.factory.config.AutowireCapableBeanFactory#createBean}. 894 * @param context the current WebApplicationContext 895 * @param clazz the strategy implementation class to instantiate 896 * @return the fully configured strategy instance 897 * @see org.springframework.context.ApplicationContext#getAutowireCapableBeanFactory() 898 * @see org.springframework.beans.factory.config.AutowireCapableBeanFactory#createBean 899 */ 900 protected Object createDefaultStrategy(ApplicationContext context, Class<?> clazz) { 901 return context.getAutowireCapableBeanFactory().createBean(clazz); 902 } 903 904 905 /** 906 * Exposes the DispatcherServlet-specific request attributes and delegates to {@link #doDispatch} 907 * for the actual dispatching. 908 */ 909 @Override 910 protected void doService(HttpServletRequest request, HttpServletResponse response) throws Exception { 911 logRequest(request); 912 913 // Keep a snapshot of the request attributes in case of an include, 914 // to be able to restore the original attributes after the include. 915 Map<String, Object> attributesSnapshot = null; 916 if (WebUtils.isIncludeRequest(request)) { 917 attributesSnapshot = new HashMap<>(); 918 Enumeration<?> attrNames = request.getAttributeNames(); 919 while (attrNames.hasMoreElements()) { 920 String attrName = (String) attrNames.nextElement(); 921 if (this.cleanupAfterInclude || attrName.startsWith(DEFAULT_STRATEGIES_PREFIX)) { 922 attributesSnapshot.put(attrName, request.getAttribute(attrName)); 923 } 924 } 925 } 926 927 // Make framework objects available to handlers and view objects. 928 request.setAttribute(WEB_APPLICATION_CONTEXT_ATTRIBUTE, getWebApplicationContext()); 929 request.setAttribute(LOCALE_RESOLVER_ATTRIBUTE, this.localeResolver); 930 request.setAttribute(THEME_RESOLVER_ATTRIBUTE, this.themeResolver); 931 request.setAttribute(THEME_SOURCE_ATTRIBUTE, getThemeSource()); 932 933 if (this.flashMapManager != null) { 934 FlashMap inputFlashMap = this.flashMapManager.retrieveAndUpdate(request, response); 935 if (inputFlashMap != null) { 936 request.setAttribute(INPUT_FLASH_MAP_ATTRIBUTE, Collections.unmodifiableMap(inputFlashMap)); 937 } 938 request.setAttribute(OUTPUT_FLASH_MAP_ATTRIBUTE, new FlashMap()); 939 request.setAttribute(FLASH_MAP_MANAGER_ATTRIBUTE, this.flashMapManager); 940 } 941 942 try { 943 doDispatch(request, response); 944 } 945 finally { 946 if (!WebAsyncUtils.getAsyncManager(request).isConcurrentHandlingStarted()) { 947 // Restore the original attribute snapshot, in case of an include. 948 if (attributesSnapshot != null) { 949 restoreAttributesAfterInclude(request, attributesSnapshot); 950 } 951 } 952 } 953 } 954 955 private void logRequest(HttpServletRequest request) { 956 LogFormatUtils.traceDebug(logger, traceOn -> { 957 String params; 958 if (isEnableLoggingRequestDetails()) { 959 params = request.getParameterMap().entrySet().stream() 960 .map(entry -> entry.getKey() + ":" + Arrays.toString(entry.getValue())) 961 .collect(Collectors.joining(", ")); 962 } 963 else { 964 params = (request.getParameterMap().isEmpty() ? "" : "masked"); 965 } 966 967 String queryString = request.getQueryString(); 968 String queryClause = (StringUtils.hasLength(queryString) ? "?" + queryString : ""); 969 String dispatchType = (!request.getDispatcherType().equals(DispatcherType.REQUEST) ? 970 "\"" + request.getDispatcherType().name() + "\" dispatch for " : ""); 971 String message = (dispatchType + request.getMethod() + " \"" + getRequestUri(request) + 972 queryClause + "\", parameters={" + params + "}"); 973 974 if (traceOn) { 975 List<String> values = Collections.list(request.getHeaderNames()); 976 String headers = values.size() > 0 ? "masked" : ""; 977 if (isEnableLoggingRequestDetails()) { 978 headers = values.stream().map(name -> name + ":" + Collections.list(request.getHeaders(name))) 979 .collect(Collectors.joining(", ")); 980 } 981 return message + ", headers={" + headers + "} in DispatcherServlet '" + getServletName() + "'"; 982 } 983 else { 984 return message; 985 } 986 }); 987 } 988 989 /** 990 * Process the actual dispatching to the handler. 991 * <p>The handler will be obtained by applying the servlet's HandlerMappings in order. 992 * The HandlerAdapter will be obtained by querying the servlet's installed HandlerAdapters 993 * to find the first that supports the handler class. 994 * <p>All HTTP methods are handled by this method. It's up to HandlerAdapters or handlers 995 * themselves to decide which methods are acceptable. 996 * @param request current HTTP request 997 * @param response current HTTP response 998 * @throws Exception in case of any kind of processing failure 999 */ 1000 protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception { 1001 HttpServletRequest processedRequest = request; 1002 HandlerExecutionChain mappedHandler = null; 1003 boolean multipartRequestParsed = false; 1004 1005 WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request); 1006 1007 try { 1008 ModelAndView mv = null; 1009 Exception dispatchException = null; 1010 1011 try { 1012 processedRequest = checkMultipart(request); 1013 multipartRequestParsed = (processedRequest != request); 1014 1015 // Determine handler for the current request. 1016 mappedHandler = getHandler(processedRequest); 1017 if (mappedHandler == null) { 1018 noHandlerFound(processedRequest, response); 1019 return; 1020 } 1021 1022 // Determine handler adapter for the current request. 1023 HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler()); 1024 1025 // Process last-modified header, if supported by the handler. 1026 String method = request.getMethod(); 1027 boolean isGet = "GET".equals(method); 1028 if (isGet || "HEAD".equals(method)) { 1029 long lastModified = ha.getLastModified(request, mappedHandler.getHandler()); 1030 if (new ServletWebRequest(request, response).checkNotModified(lastModified) && isGet) { 1031 return; 1032 } 1033 } 1034 1035 if (!mappedHandler.applyPreHandle(processedRequest, response)) { 1036 return; 1037 } 1038 1039 // Actually invoke the handler. 1040 mv = ha.handle(processedRequest, response, mappedHandler.getHandler()); 1041 1042 if (asyncManager.isConcurrentHandlingStarted()) { 1043 return; 1044 } 1045 1046 applyDefaultViewName(processedRequest, mv); 1047 mappedHandler.applyPostHandle(processedRequest, response, mv); 1048 } 1049 catch (Exception ex) { 1050 dispatchException = ex; 1051 } 1052 catch (Throwable err) { 1053 // As of 4.3, we're processing Errors thrown from handler methods as well, 1054 // making them available for @ExceptionHandler methods and other scenarios. 1055 dispatchException = new NestedServletException("Handler dispatch failed", err); 1056 } 1057 processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException); 1058 } 1059 catch (Exception ex) { 1060 triggerAfterCompletion(processedRequest, response, mappedHandler, ex); 1061 } 1062 catch (Throwable err) { 1063 triggerAfterCompletion(processedRequest, response, mappedHandler, 1064 new NestedServletException("Handler processing failed", err)); 1065 } 1066 finally { 1067 if (asyncManager.isConcurrentHandlingStarted()) { 1068 // Instead of postHandle and afterCompletion 1069 if (mappedHandler != null) { 1070 mappedHandler.applyAfterConcurrentHandlingStarted(processedRequest, response); 1071 } 1072 } 1073 else { 1074 // Clean up any resources used by a multipart request. 1075 if (multipartRequestParsed) { 1076 cleanupMultipart(processedRequest); 1077 } 1078 } 1079 } 1080 } 1081 1082 /** 1083 * Do we need view name translation? 1084 */ 1085 private void applyDefaultViewName(HttpServletRequest request, @Nullable ModelAndView mv) throws Exception { 1086 if (mv != null && !mv.hasView()) { 1087 String defaultViewName = getDefaultViewName(request); 1088 if (defaultViewName != null) { 1089 mv.setViewName(defaultViewName); 1090 } 1091 } 1092 } 1093 1094 /** 1095 * Handle the result of handler selection and handler invocation, which is 1096 * either a ModelAndView or an Exception to be resolved to a ModelAndView. 1097 */ 1098 private void processDispatchResult(HttpServletRequest request, HttpServletResponse response, 1099 @Nullable HandlerExecutionChain mappedHandler, @Nullable ModelAndView mv, 1100 @Nullable Exception exception) throws Exception { 1101 1102 boolean errorView = false; 1103 1104 if (exception != null) { 1105 if (exception instanceof ModelAndViewDefiningException) { 1106 logger.debug("ModelAndViewDefiningException encountered", exception); 1107 mv = ((ModelAndViewDefiningException) exception).getModelAndView(); 1108 } 1109 else { 1110 Object handler = (mappedHandler != null ? mappedHandler.getHandler() : null); 1111 mv = processHandlerException(request, response, handler, exception); 1112 errorView = (mv != null); 1113 } 1114 } 1115 1116 // Did the handler return a view to render? 1117 if (mv != null && !mv.wasCleared()) { 1118 render(mv, request, response); 1119 if (errorView) { 1120 WebUtils.clearErrorRequestAttributes(request); 1121 } 1122 } 1123 else { 1124 if (logger.isTraceEnabled()) { 1125 logger.trace("No view rendering, null ModelAndView returned."); 1126 } 1127 } 1128 1129 if (WebAsyncUtils.getAsyncManager(request).isConcurrentHandlingStarted()) { 1130 // Concurrent handling started during a forward 1131 return; 1132 } 1133 1134 if (mappedHandler != null) { 1135 // Exception (if any) is already handled.. 1136 mappedHandler.triggerAfterCompletion(request, response, null); 1137 } 1138 } 1139 1140 /** 1141 * Build a LocaleContext for the given request, exposing the request's primary locale as current locale. 1142 * <p>The default implementation uses the dispatcher's LocaleResolver to obtain the current locale, 1143 * which might change during a request. 1144 * @param request current HTTP request 1145 * @return the corresponding LocaleContext 1146 */ 1147 @Override 1148 protected LocaleContext buildLocaleContext(final HttpServletRequest request) { 1149 LocaleResolver lr = this.localeResolver; 1150 if (lr instanceof LocaleContextResolver) { 1151 return ((LocaleContextResolver) lr).resolveLocaleContext(request); 1152 } 1153 else { 1154 return () -> (lr != null ? lr.resolveLocale(request) : request.getLocale()); 1155 } 1156 } 1157 1158 /** 1159 * Convert the request into a multipart request, and make multipart resolver available. 1160 * <p>If no multipart resolver is set, simply use the existing request. 1161 * @param request current HTTP request 1162 * @return the processed request (multipart wrapper if necessary) 1163 * @see MultipartResolver#resolveMultipart 1164 */ 1165 protected HttpServletRequest checkMultipart(HttpServletRequest request) throws MultipartException { 1166 if (this.multipartResolver != null && this.multipartResolver.isMultipart(request)) { 1167 if (WebUtils.getNativeRequest(request, MultipartHttpServletRequest.class) != null) { 1168 if (request.getDispatcherType().equals(DispatcherType.REQUEST)) { 1169 logger.trace("Request already resolved to MultipartHttpServletRequest, e.g. by MultipartFilter"); 1170 } 1171 } 1172 else if (hasMultipartException(request)) { 1173 logger.debug("Multipart resolution previously failed for current request - " + 1174 "skipping re-resolution for undisturbed error rendering"); 1175 } 1176 else { 1177 try { 1178 return this.multipartResolver.resolveMultipart(request); 1179 } 1180 catch (MultipartException ex) { 1181 if (request.getAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE) != null) { 1182 logger.debug("Multipart resolution failed for error dispatch", ex); 1183 // Keep processing error dispatch with regular request handle below 1184 } 1185 else { 1186 throw ex; 1187 } 1188 } 1189 } 1190 } 1191 // If not returned before: return original request. 1192 return request; 1193 } 1194 1195 /** 1196 * Check "javax.servlet.error.exception" attribute for a multipart exception. 1197 */ 1198 private boolean hasMultipartException(HttpServletRequest request) { 1199 Throwable error = (Throwable) request.getAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE); 1200 while (error != null) { 1201 if (error instanceof MultipartException) { 1202 return true; 1203 } 1204 error = error.getCause(); 1205 } 1206 return false; 1207 } 1208 1209 /** 1210 * Clean up any resources used by the given multipart request (if any). 1211 * @param request current HTTP request 1212 * @see MultipartResolver#cleanupMultipart 1213 */ 1214 protected void cleanupMultipart(HttpServletRequest request) { 1215 if (this.multipartResolver != null) { 1216 MultipartHttpServletRequest multipartRequest = 1217 WebUtils.getNativeRequest(request, MultipartHttpServletRequest.class); 1218 if (multipartRequest != null) { 1219 this.multipartResolver.cleanupMultipart(multipartRequest); 1220 } 1221 } 1222 } 1223 1224 /** 1225 * Return the HandlerExecutionChain for this request. 1226 * <p>Tries all handler mappings in order. 1227 * @param request current HTTP request 1228 * @return the HandlerExecutionChain, or {@code null} if no handler could be found 1229 */ 1230 @Nullable 1231 protected HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception { 1232 if (this.handlerMappings != null) { 1233 for (HandlerMapping mapping : this.handlerMappings) { 1234 HandlerExecutionChain handler = mapping.getHandler(request); 1235 if (handler != null) { 1236 return handler; 1237 } 1238 } 1239 } 1240 return null; 1241 } 1242 1243 /** 1244 * No handler found -> set appropriate HTTP response status. 1245 * @param request current HTTP request 1246 * @param response current HTTP response 1247 * @throws Exception if preparing the response failed 1248 */ 1249 protected void noHandlerFound(HttpServletRequest request, HttpServletResponse response) throws Exception { 1250 if (pageNotFoundLogger.isWarnEnabled()) { 1251 pageNotFoundLogger.warn("No mapping for " + request.getMethod() + " " + getRequestUri(request)); 1252 } 1253 if (this.throwExceptionIfNoHandlerFound) { 1254 throw new NoHandlerFoundException(request.getMethod(), getRequestUri(request), 1255 new ServletServerHttpRequest(request).getHeaders()); 1256 } 1257 else { 1258 response.sendError(HttpServletResponse.SC_NOT_FOUND); 1259 } 1260 } 1261 1262 /** 1263 * Return the HandlerAdapter for this handler object. 1264 * @param handler the handler object to find an adapter for 1265 * @throws ServletException if no HandlerAdapter can be found for the handler. This is a fatal error. 1266 */ 1267 protected HandlerAdapter getHandlerAdapter(Object handler) throws ServletException { 1268 if (this.handlerAdapters != null) { 1269 for (HandlerAdapter adapter : this.handlerAdapters) { 1270 if (adapter.supports(handler)) { 1271 return adapter; 1272 } 1273 } 1274 } 1275 throw new ServletException("No adapter for handler [" + handler + 1276 "]: The DispatcherServlet configuration needs to include a HandlerAdapter that supports this handler"); 1277 } 1278 1279 /** 1280 * Determine an error ModelAndView via the registered HandlerExceptionResolvers. 1281 * @param request current HTTP request 1282 * @param response current HTTP response 1283 * @param handler the executed handler, or {@code null} if none chosen at the time of the exception 1284 * (for example, if multipart resolution failed) 1285 * @param ex the exception that got thrown during handler execution 1286 * @return a corresponding ModelAndView to forward to 1287 * @throws Exception if no error ModelAndView found 1288 */ 1289 @Nullable 1290 protected ModelAndView processHandlerException(HttpServletRequest request, HttpServletResponse response, 1291 @Nullable Object handler, Exception ex) throws Exception { 1292 1293 // Success and error responses may use different content types 1294 request.removeAttribute(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE); 1295 1296 // Check registered HandlerExceptionResolvers... 1297 ModelAndView exMv = null; 1298 if (this.handlerExceptionResolvers != null) { 1299 for (HandlerExceptionResolver resolver : this.handlerExceptionResolvers) { 1300 exMv = resolver.resolveException(request, response, handler, ex); 1301 if (exMv != null) { 1302 break; 1303 } 1304 } 1305 } 1306 if (exMv != null) { 1307 if (exMv.isEmpty()) { 1308 request.setAttribute(EXCEPTION_ATTRIBUTE, ex); 1309 return null; 1310 } 1311 // We might still need view name translation for a plain error model... 1312 if (!exMv.hasView()) { 1313 String defaultViewName = getDefaultViewName(request); 1314 if (defaultViewName != null) { 1315 exMv.setViewName(defaultViewName); 1316 } 1317 } 1318 if (logger.isTraceEnabled()) { 1319 logger.trace("Using resolved error view: " + exMv, ex); 1320 } 1321 else if (logger.isDebugEnabled()) { 1322 logger.debug("Using resolved error view: " + exMv); 1323 } 1324 WebUtils.exposeErrorRequestAttributes(request, ex, getServletName()); 1325 return exMv; 1326 } 1327 1328 throw ex; 1329 } 1330 1331 /** 1332 * Render the given ModelAndView. 1333 * <p>This is the last stage in handling a request. It may involve resolving the view by name. 1334 * @param mv the ModelAndView to render 1335 * @param request current HTTP servlet request 1336 * @param response current HTTP servlet response 1337 * @throws ServletException if view is missing or cannot be resolved 1338 * @throws Exception if there's a problem rendering the view 1339 */ 1340 protected void render(ModelAndView mv, HttpServletRequest request, HttpServletResponse response) throws Exception { 1341 // Determine locale for request and apply it to the response. 1342 Locale locale = 1343 (this.localeResolver != null ? this.localeResolver.resolveLocale(request) : request.getLocale()); 1344 response.setLocale(locale); 1345 1346 View view; 1347 String viewName = mv.getViewName(); 1348 if (viewName != null) { 1349 // We need to resolve the view name. 1350 view = resolveViewName(viewName, mv.getModelInternal(), locale, request); 1351 if (view == null) { 1352 throw new ServletException("Could not resolve view with name '" + mv.getViewName() + 1353 "' in servlet with name '" + getServletName() + "'"); 1354 } 1355 } 1356 else { 1357 // No need to lookup: the ModelAndView object contains the actual View object. 1358 view = mv.getView(); 1359 if (view == null) { 1360 throw new ServletException("ModelAndView [" + mv + "] neither contains a view name nor a " + 1361 "View object in servlet with name '" + getServletName() + "'"); 1362 } 1363 } 1364 1365 // Delegate to the View object for rendering. 1366 if (logger.isTraceEnabled()) { 1367 logger.trace("Rendering view [" + view + "] "); 1368 } 1369 try { 1370 if (mv.getStatus() != null) { 1371 response.setStatus(mv.getStatus().value()); 1372 } 1373 view.render(mv.getModelInternal(), request, response); 1374 } 1375 catch (Exception ex) { 1376 if (logger.isDebugEnabled()) { 1377 logger.debug("Error rendering view [" + view + "]", ex); 1378 } 1379 throw ex; 1380 } 1381 } 1382 1383 /** 1384 * Translate the supplied request into a default view name. 1385 * @param request current HTTP servlet request 1386 * @return the view name (or {@code null} if no default found) 1387 * @throws Exception if view name translation failed 1388 */ 1389 @Nullable 1390 protected String getDefaultViewName(HttpServletRequest request) throws Exception { 1391 return (this.viewNameTranslator != null ? this.viewNameTranslator.getViewName(request) : null); 1392 } 1393 1394 /** 1395 * Resolve the given view name into a View object (to be rendered). 1396 * <p>The default implementations asks all ViewResolvers of this dispatcher. 1397 * Can be overridden for custom resolution strategies, potentially based on 1398 * specific model attributes or request parameters. 1399 * @param viewName the name of the view to resolve 1400 * @param model the model to be passed to the view 1401 * @param locale the current locale 1402 * @param request current HTTP servlet request 1403 * @return the View object, or {@code null} if none found 1404 * @throws Exception if the view cannot be resolved 1405 * (typically in case of problems creating an actual View object) 1406 * @see ViewResolver#resolveViewName 1407 */ 1408 @Nullable 1409 protected View resolveViewName(String viewName, @Nullable Map<String, Object> model, 1410 Locale locale, HttpServletRequest request) throws Exception { 1411 1412 if (this.viewResolvers != null) { 1413 for (ViewResolver viewResolver : this.viewResolvers) { 1414 View view = viewResolver.resolveViewName(viewName, locale); 1415 if (view != null) { 1416 return view; 1417 } 1418 } 1419 } 1420 return null; 1421 } 1422 1423 private void triggerAfterCompletion(HttpServletRequest request, HttpServletResponse response, 1424 @Nullable HandlerExecutionChain mappedHandler, Exception ex) throws Exception { 1425 1426 if (mappedHandler != null) { 1427 mappedHandler.triggerAfterCompletion(request, response, ex); 1428 } 1429 throw ex; 1430 } 1431 1432 /** 1433 * Restore the request attributes after an include. 1434 * @param request current HTTP request 1435 * @param attributesSnapshot the snapshot of the request attributes before the include 1436 */ 1437 @SuppressWarnings("unchecked") 1438 private void restoreAttributesAfterInclude(HttpServletRequest request, Map<?, ?> attributesSnapshot) { 1439 // Need to copy into separate Collection here, to avoid side effects 1440 // on the Enumeration when removing attributes. 1441 Set<String> attrsToCheck = new HashSet<>(); 1442 Enumeration<?> attrNames = request.getAttributeNames(); 1443 while (attrNames.hasMoreElements()) { 1444 String attrName = (String) attrNames.nextElement(); 1445 if (this.cleanupAfterInclude || attrName.startsWith(DEFAULT_STRATEGIES_PREFIX)) { 1446 attrsToCheck.add(attrName); 1447 } 1448 } 1449 1450 // Add attributes that may have been removed 1451 attrsToCheck.addAll((Set<String>) attributesSnapshot.keySet()); 1452 1453 // Iterate over the attributes to check, restoring the original value 1454 // or removing the attribute, respectively, if appropriate. 1455 for (String attrName : attrsToCheck) { 1456 Object attrValue = attributesSnapshot.get(attrName); 1457 if (attrValue == null) { 1458 request.removeAttribute(attrName); 1459 } 1460 else if (attrValue != request.getAttribute(attrName)) { 1461 request.setAttribute(attrName, attrValue); 1462 } 1463 } 1464 } 1465 1466 private static String getRequestUri(HttpServletRequest request) { 1467 String uri = (String) request.getAttribute(WebUtils.INCLUDE_REQUEST_URI_ATTRIBUTE); 1468 if (uri == null) { 1469 uri = request.getRequestURI(); 1470 } 1471 return uri; 1472 } 1473 1474}