Top Description Fields Constructors Methods
org.springframework.web.servlet

public Class DispatcherServlet

extends FrameworkServlet
Class Inheritance
Annotations
@SuppressWarnings:serial
Imports
java.io.IOException, java.util.ArrayList, .Arrays, .Collections, .Enumeration, .HashMap, .HashSet, .List, .Locale, .Map, .Properties, .Set, java.util.stream.Collectors, jakarta.servlet.DispatcherType, .ServletContext, .ServletException, jakarta.servlet.http.HttpServletRequest, .HttpServletResponse, org.apache.commons.logging.Log, .LogFactory, org.springframework.beans.factory.BeanFactoryUtils, .BeanInitializationException, .NoSuchBeanDefinitionException, org.springframework.context.ApplicationContext, .ConfigurableApplicationContext, org.springframework.context.i18n.LocaleContext, org.springframework.core.annotation.AnnotationAwareOrderComparator, org.springframework.core.io.ClassPathResource, org.springframework.core.io.support.PropertiesLoaderUtils, org.springframework.core.log.LogFormatUtils, org.springframework.http.HttpMethod, .MediaType, org.springframework.http.server.RequestPath, .ServletServerHttpRequest, org.springframework.lang.Nullable, org.springframework.util.ClassUtils, .StringUtils, org.springframework.web.context.WebApplicationContext, org.springframework.web.context.request.ServletWebRequest, org.springframework.web.context.request.async.WebAsyncManager, .WebAsyncUtils, org.springframework.web.multipart.MultipartException, .MultipartHttpServletRequest, .MultipartResolver, org.springframework.web.util.ServletRequestPathUtils, .WebUtils

Central dispatcher for HTTP request handlers/controllers, e.g. for web UI controllers or HTTP-based remote service exporters. Dispatches to registered handlers for processing a web request, providing convenient mapping and exception handling facilities.

This servlet is very flexible: It can be used with just about any workflow, with the installation of the appropriate adapter classes. It offers the following functionality that distinguishes it from other request-driven web MVC frameworks:

NOTE: The @RequestMapping annotation will only be processed if a corresponding HandlerMapping (for type-level annotations) and/or HandlerAdapter (for method-level annotations) is present in the dispatcher. This is the case by default. However, if you are defining custom HandlerMappings or HandlerAdapters, then you need to make sure that a corresponding custom RequestMappingHandlerMapping and/or RequestMappingHandlerAdapter is defined as well - provided that you intend to use @RequestMapping.

A web application can define any number of DispatcherServlets. Each servlet will operate in its own namespace, loading its own application context with mappings, handlers, etc. Only the root application context as loaded by org.springframework.web.context.ContextLoaderListener, if any, will be shared.

DispatcherServlet may be injected with a web application context, rather than creating its own internally. This is useful in Servlet 3.0+ environments, which support programmatic registration of servlet instances. See the DispatcherServlet(WebApplicationContext) javadoc for details.

Authors
Rod Johnson, Juergen Hoeller, Rob Harrop, Chris Beams, Rossen Stoyanchev, Sebastien Deleuze
See Also
org.springframework.web.HttpRequestHandler, org.springframework.web.servlet.mvc.Controller, org.springframework.web.context.ContextLoaderListener

Field Summary

Modifier and TypeField and Description
private boolean
cleanupAfterInclude

Perform cleanup of request attributes after include request?.

private static final String
DEFAULT_STRATEGIES_PATH

Name of the class path resource (relative to the DispatcherServlet class) that defines DispatcherServlet's default strategy names.

private static final String
DEFAULT_STRATEGIES_PREFIX

Common prefix that DispatcherServlet's default strategy attributes start with.

private static Properties
defaultStrategies

Store default strategy implementations.

private boolean
detectAllHandlerAdapters

Detect all HandlerAdapters or just expect "handlerAdapter" bean?.

private boolean
detectAllHandlerExceptionResolvers

Detect all HandlerExceptionResolvers or just expect "handlerExceptionResolver" bean?.

private boolean
detectAllHandlerMappings

Detect all HandlerMappings or just expect "handlerMapping" bean?.

private boolean
detectAllViewResolvers

Detect all ViewResolvers or just expect "viewResolver" bean?.

public static final String
EXCEPTION_ATTRIBUTE

Name of request attribute that exposes an Exception resolved with a HandlerExceptionResolver but where no view was rendered (e.g. setting the status code).

public static final String
FLASH_MAP_MANAGER_ATTRIBUTE

Name of request attribute that holds the FlashMapManager.

public static final String
FLASH_MAP_MANAGER_BEAN_NAME

Well-known name for the FlashMapManager object in the bean factory for this namespace.

private FlashMapManager
flashMapManager

FlashMapManager used by this servlet.

public static final String
HANDLER_ADAPTER_BEAN_NAME

Well-known name for the HandlerAdapter object in the bean factory for this namespace.

public static final String
HANDLER_EXCEPTION_RESOLVER_BEAN_NAME

Well-known name for the HandlerExceptionResolver object in the bean factory for this namespace.

public static final String
HANDLER_MAPPING_BEAN_NAME

Well-known name for the HandlerMapping object in the bean factory for this namespace.

private List<HandlerAdapter>
handlerAdapters

List of HandlerAdapters used by this servlet.

private List<HandlerExceptionResolver>
handlerExceptionResolvers

List of HandlerExceptionResolvers used by this servlet.

private List<HandlerMapping>
handlerMappings

List of HandlerMappings used by this servlet.

public static final String
INPUT_FLASH_MAP_ATTRIBUTE

Name of request attribute that holds a read-only Map<String,?

public static final String
LOCALE_RESOLVER_ATTRIBUTE

Request attribute to hold the current LocaleResolver, retrievable by views.

public static final String
LOCALE_RESOLVER_BEAN_NAME

Well-known name for the LocaleResolver object in the bean factory for this namespace.

private LocaleResolver
localeResolver

LocaleResolver used by this servlet.

public static final String
MULTIPART_RESOLVER_BEAN_NAME

Well-known name for the MultipartResolver object in the bean factory for this namespace.

private MultipartResolver
multipartResolver

MultipartResolver used by this servlet.

public static final String
OUTPUT_FLASH_MAP_ATTRIBUTE

Name of request attribute that holds the "output" FlashMap with attributes to save for a subsequent request.

public static final String
PAGE_NOT_FOUND_LOG_CATEGORY

Log category to use when no mapped handler is found for a request.

protected static final Log
pageNotFoundLogger

Additional logger to use when no mapped handler is found for a request.

private boolean
public static final String
REQUEST_TO_VIEW_NAME_TRANSLATOR_BEAN_NAME

Well-known name for the RequestToViewNameTranslator object in the bean factory for this namespace.

public static final String
THEME_RESOLVER_ATTRIBUTE

Deprecated as of 6.0, with no direct replacement
Request attribute to hold the current ThemeResolver, retrievable by views.
public static final String
THEME_RESOLVER_BEAN_NAME

Deprecated as of 6.0, with no direct replacement
Well-known name for the ThemeResolver object in the bean factory for this namespace.
public static final String
THEME_SOURCE_ATTRIBUTE

Deprecated as of 6.0, with no direct replacement
Request attribute to hold the current ThemeSource, retrievable by views.
private ThemeResolver
themeResolver

Deprecated
ThemeResolver used by this servlet.
private boolean
throwExceptionIfNoHandlerFound

Throw a NoHandlerFoundException if no Handler was found to process this request?

public static final String
VIEW_RESOLVER_BEAN_NAME

Well-known name for the ViewResolver object in the bean factory for this namespace.

private RequestToViewNameTranslator
viewNameTranslator

RequestToViewNameTranslator used by this servlet.

private List<ViewResolver>
viewResolvers

List of ViewResolvers used by this servlet.

public static final String
WEB_APPLICATION_CONTEXT_ATTRIBUTE

Request attribute to hold the current web application context.

Inherited from org.springframework.web.servlet.FrameworkServlet:
DEFAULT_CONTEXT_CLASSDEFAULT_NAMESPACE_SUFFIXSERVLET_CONTEXT_PREFIX

Constructor Summary

AccessConstructor and Description
public
DispatcherServlet()

Create a new DispatcherServlet that will create its own internal web application context based on defaults and values provided through servlet init-params.

public
DispatcherServlet(WebApplicationContext
the context to use
webApplicationContext
)

Create a new DispatcherServlet with the given web application context.

Method Summary

Modifier and TypeMethod and Description
private void
applyDefaultViewName(HttpServletRequest request, ModelAndView mv)

Do we need view name translation?

protected LocaleContext

Returns:

the corresponding LocaleContext
buildLocaleContext
(final HttpServletRequest
current HTTP request
request
)

Overrides org.springframework.web.servlet.FrameworkServlet.buildLocaleContext.

Build a LocaleContext for the given request, exposing the request's primary locale as current locale.

protected HttpServletRequest

Returns:

the processed request (multipart wrapper if necessary)
checkMultipart
(HttpServletRequest
current HTTP request
request
)

Convert the request into a multipart request, and make multipart resolver available.

protected void
cleanupMultipart(HttpServletRequest
current HTTP request
request
)

Clean up any resources used by the given multipart request (if any).

protected Object

Returns:

the fully configured strategy instance
createDefaultStrategy
(ApplicationContext
the current WebApplicationContext
context
,
Class<?>
the strategy implementation class to instantiate
clazz
)

Create a default strategy.

protected void
doDispatch(HttpServletRequest
current HTTP request
request
,
HttpServletResponse
current HTTP response
response
)

Process the actual dispatching to the handler.

protected void
doService(HttpServletRequest
current HTTP request
request
,
HttpServletResponse
current HTTP response
response
)

Implements abstract org.springframework.web.servlet.FrameworkServlet.doService.

Exposes the DispatcherServlet-specific request attributes and delegates to doDispatch for the actual dispatching.

protected <T> List<T>

Returns:

the List of corresponding strategy objects
getDefaultStrategies
(ApplicationContext
the current WebApplicationContext
context
,
Class<T>
the strategy interface
strategyInterface
)

Create a List of default strategy objects for the given strategy interface.

protected <T> T

Returns:

the corresponding strategy object
getDefaultStrategy
(ApplicationContext
the current WebApplicationContext
context
,
Class<T>
the strategy interface
strategyInterface
)

Return the default strategy object for the given strategy interface.

protected String

Returns:

the view name (or null if no default found)
getDefaultViewName
(HttpServletRequest
current HTTP servlet request
request
)

Translate the supplied request into a default view name.

protected HandlerExecutionChain

Returns:

the HandlerExecutionChain, or null if no handler could be found
getHandler
(HttpServletRequest
current HTTP request
request
)

Return the HandlerExecutionChain for this request.

protected HandlerAdapter
getHandlerAdapter(Object
the handler object to find an adapter for
handler
)

Return the HandlerAdapter for this handler object.

public final List<HandlerMapping>

Returns:

an immutable list with the configured mappings, or null if not initialized yet
getHandlerMappings
()

Return the configured HandlerMapping beans that were detected by type in the WebApplicationContext or initialized based on the default set of strategies from DispatcherServlet.properties.

public final MultipartResolver

Returns:

the MultipartResolver used by this servlet, or null if none (indicating that no multipart support is available)
getMultipartResolver
()

Obtain this servlet's MultipartResolver, if any.

private static String
public final ThemeSource

Returns:

the ThemeSource, if any
getThemeSource
()
Deprecated

Return this servlet's ThemeSource, if any; else return null.

private static boolean
hasMultipartException(HttpServletRequest request)

Check "jakarta.servlet.error.exception" attribute for a multipart exception.

private void
initFlashMapManager(ApplicationContext context)

Initialize the FlashMapManager used by this servlet instance.

private void
initHandlerAdapters(ApplicationContext context)

Initialize the HandlerAdapters used by this class.

private void
initHandlerExceptionResolvers(ApplicationContext context)

Initialize the HandlerExceptionResolver used by this class.

private void
initHandlerMappings(ApplicationContext context)

Initialize the HandlerMappings used by this class.

private void
initLocaleResolver(ApplicationContext context)

Initialize the LocaleResolver used by this class.

private void
initMultipartResolver(ApplicationContext context)

Initialize the MultipartResolver used by this class.

private void
initRequestToViewNameTranslator(ApplicationContext context)

Initialize the RequestToViewNameTranslator used by this servlet instance.

protected void
initStrategies(ApplicationContext context)

Initialize the strategy objects that this servlet uses.

private void
initThemeResolver(ApplicationContext context)
Deprecated

Initialize the ThemeResolver used by this class.

private void
initViewResolvers(ApplicationContext context)

Initialize the ViewResolvers used by this class.

private void
protected void
noHandlerFound(HttpServletRequest
current HTTP request
request
,
HttpServletResponse
current HTTP response
response
)

No handler found → set appropriate HTTP response status.

protected void
onRefresh(ApplicationContext
the current WebApplicationContext
context
)

Overrides org.springframework.web.servlet.FrameworkServlet.onRefresh.

This implementation calls initStrategies.

private void
processDispatchResult(HttpServletRequest request, HttpServletResponse response, HandlerExecutionChain mappedHandler, ModelAndView mv, Exception exception)

Handle the result of handler selection and handler invocation, which is either a ModelAndView or an Exception to be resolved to a ModelAndView.

protected ModelAndView

Returns:

a corresponding ModelAndView to forward to
processHandlerException
(HttpServletRequest
current HTTP request
request
,
HttpServletResponse
current HTTP response
response
,
Object
the executed handler, or null if none chosen at the time of the exception (for example, if multipart resolution failed)
handler
,
Exception
the exception that got thrown during handler execution
ex
)

Determine an error ModelAndView via the registered HandlerExceptionResolvers.

protected void
render(ModelAndView
the ModelAndView to render
mv
,
HttpServletRequest
current HTTP servlet request
request
,
HttpServletResponse
current HTTP servlet response
response
)

Render the given ModelAndView.

protected View

Returns:

the View object, or null if none found
resolveViewName
(String
the name of the view to resolve
viewName
,
Map<String, Object>
the model to be passed to the view
model
,
Locale
the current locale
locale
,
HttpServletRequest
current HTTP servlet request
request
)

Resolve the given view name into a View object (to be rendered).

private void
restoreAttributesAfterInclude(HttpServletRequest
current HTTP request
request
,
Map<?, ?>
the snapshot of the request attributes before the include
attributesSnapshot
)

Restore the request attributes after an include.

public void
setCleanupAfterInclude(boolean cleanupAfterInclude)

Set whether to perform cleanup of request attributes after an include request, that is, whether to reset the original state of all request attributes after the DispatcherServlet has processed within an include request.

public void
setDetectAllHandlerAdapters(boolean detectAllHandlerAdapters)

Set whether to detect all HandlerAdapter beans in this servlet's context.

public void
setDetectAllHandlerExceptionResolvers(boolean detectAllHandlerExceptionResolvers)

Set whether to detect all HandlerExceptionResolver beans in this servlet's context.

public void
setDetectAllHandlerMappings(boolean detectAllHandlerMappings)

Set whether to detect all HandlerMapping beans in this servlet's context.

public void
setDetectAllViewResolvers(boolean detectAllViewResolvers)

Set whether to detect all ViewResolver beans in this servlet's context.

public void
setThrowExceptionIfNoHandlerFound(boolean throwExceptionIfNoHandlerFound)
Deprecated for removal since 6.1. as of 6.1 this property is set to true by default, and should not need to be customized; in effect, DispatcherServlet should always raise NoHandlerFoundException and allow it to be handled through a HandlerExceptionResolver.

Set whether to throw a NoHandlerFoundException when no Handler was found for this request.

private static void
Inherited from org.springframework.web.servlet.FrameworkServlet:
applyInitializersbuildRequestAttributesconfigureAndRefreshWebApplicationContextcreateWebApplicationContextcreateWebApplicationContextdestroydoDeletedoGetdoOptionsdoPostdoPutdoTracefindWebApplicationContextgetContextAttributegetContextClassgetContextConfigLocationgetContextIdgetNamespacegetServletContextAttributeNamegetUsernameForRequestgetWebApplicationContextinitFrameworkServletinitServletBeaninitWebApplicationContextisEnableLoggingRequestDetailsonApplicationEventpostProcessWebApplicationContextprocessRequestrefreshservicesetApplicationContextsetContextAttributesetContextClasssetContextConfigLocationsetContextIdsetContextInitializerClassessetContextInitializerssetDispatchOptionsRequestsetDispatchTraceRequestsetEnableLoggingRequestDetailssetNamespacesetPublishContextsetPublishEventssetThreadContextInheritable