docs
Core framework classes including DispatcherServlet, handler mappings, handler adapters, and other central components that form the foundation of Spring MVC's request processing architecture.
The central servlet in Spring MVC that dispatches requests to registered handlers.
/**
* Central dispatcher for HTTP request handlers/controllers. 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:
*
* - It is based around a JavaBeans configuration mechanism.
* - It can use any HandlerMapping implementation to control routing of requests to handler objects.
* - It can use any HandlerAdapter.
* - Its exception resolution strategy can be specified via a HandlerExceptionResolver.
* - Its view resolution strategy is customizable via ViewResolver implementations.
* - Its locale resolution is customizable via LocaleResolver implementations.
* - It supports flexible theme resolution via ThemeResolver.
*/
public class DispatcherServlet extends FrameworkServlet {
/**
* Well-known name for the MultipartResolver object in the bean factory for this namespace.
*/
public static final String MULTIPART_RESOLVER_BEAN_NAME = "multipartResolver";
/**
* Well-known name for the LocaleResolver object in the bean factory for this namespace.
*/
public static final String LOCALE_RESOLVER_BEAN_NAME = "localeResolver";
/**
* Well-known name for the ThemeResolver object in the bean factory for this namespace.
*/
public static final String THEME_RESOLVER_BEAN_NAME = "themeResolver";
/**
* Well-known name for the HandlerMapping object in the bean factory for this namespace.
* Only used when "detectAllHandlerMappings" is turned off.
*/
public static final String HANDLER_MAPPING_BEAN_NAME = "handlerMapping";
/**
* Well-known name for the HandlerAdapter object in the bean factory for this namespace.
* Only used when "detectAllHandlerAdapters" is turned off.
*/
public static final String HANDLER_ADAPTER_BEAN_NAME = "handlerAdapter";
/**
* Well-known name for the HandlerExceptionResolver object in the bean factory for this namespace.
* Only used when "detectAllHandlerExceptionResolvers" is turned off.
*/
public static final String HANDLER_EXCEPTION_RESOLVER_BEAN_NAME = "handlerExceptionResolver";
/**
* Well-known name for the RequestToViewNameTranslator object in the bean factory for this namespace.
*/
public static final String REQUEST_TO_VIEW_NAME_TRANSLATOR_BEAN_NAME = "viewNameTranslator";
/**
* Well-known name for the ViewResolver object in the bean factory for this namespace.
* Only used when "detectAllViewResolvers" is turned off.
*/
public static final String VIEW_RESOLVER_BEAN_NAME = "viewResolver";
/**
* Well-known name for the FlashMapManager object in the bean factory for this namespace.
*/
public static final String FLASH_MAP_MANAGER_BEAN_NAME = "flashMapManager";
/**
* Request attribute to hold the current web application context.
*/
public static final String WEB_APPLICATION_CONTEXT_ATTRIBUTE = DispatcherServlet.class.getName() + ".CONTEXT";
/**
* Request attribute to hold the current LocaleResolver.
*/
public static final String LOCALE_RESOLVER_ATTRIBUTE = DispatcherServlet.class.getName() + ".LOCALE_RESOLVER";
/**
* Request attribute to hold the current ThemeResolver.
*/
public static final String THEME_RESOLVER_ATTRIBUTE = DispatcherServlet.class.getName() + ".THEME_RESOLVER";
/**
* Request attribute to hold the current ThemeSource.
*/
public static final String THEME_SOURCE_ATTRIBUTE = DispatcherServlet.class.getName() + ".THEME_SOURCE";
/**
* Name of request attribute that holds a read-only Map of "input" flash attributes saved
* by a previous request, if any.
*/
public static final String INPUT_FLASH_MAP_ATTRIBUTE = DispatcherServlet.class.getName() + ".INPUT_FLASH_MAP";
/**
* Name of request attribute that holds the "output" FlashMap with attributes to save for
* a subsequent request.
*/
public static final String OUTPUT_FLASH_MAP_ATTRIBUTE = DispatcherServlet.class.getName() + ".OUTPUT_FLASH_MAP";
/**
* Name of request attribute that exposes the FlashMapManager instance.
*/
public static final String FLASH_MAP_MANAGER_ATTRIBUTE = DispatcherServlet.class.getName() + ".FLASH_MAP_MANAGER";
/**
* Log category to use when no mapped handler is found for a request.
*/
public static final String PAGE_NOT_FOUND_LOG_CATEGORY = "org.springframework.web.servlet.PageNotFound";
/**
* Name of the class path resource defining DispatcherServlet's default strategy names.
*/
private static final String DEFAULT_STRATEGIES_PATH = "DispatcherServlet.properties";
/**
* Create a new DispatcherServlet that will create its own internal web application context.
*/
public DispatcherServlet() {}
/**
* Create a new DispatcherServlet with the given web application context.
*
* @param webApplicationContext the context to use
*/
public DispatcherServlet(WebApplicationContext webApplicationContext) {}
/**
* Set whether to detect all HandlerMapping beans in this servlet's context.
* Otherwise, just a single bean with name "handlerMapping" will be expected.
* Default is true. Turn off to have this servlet detect HandlerMappings only
* through a single bean.
*
* @param detectAllHandlerMappings whether to detect all handler mappings
*/
public void setDetectAllHandlerMappings(boolean detectAllHandlerMappings) {}
/**
* Set whether to detect all HandlerAdapter beans in this servlet's context.
* Default is true.
*
* @param detectAllHandlerAdapters whether to detect all handler adapters
*/
public void setDetectAllHandlerAdapters(boolean detectAllHandlerAdapters) {}
/**
* Set whether to detect all HandlerExceptionResolver beans in this servlet's context.
* Default is true.
*
* @param detectAllHandlerExceptionResolvers whether to detect all exception resolvers
*/
public void setDetectAllHandlerExceptionResolvers(boolean detectAllHandlerExceptionResolvers) {}
/**
* Set whether to detect all ViewResolver beans in this servlet's context.
* Default is true.
*
* @param detectAllViewResolvers whether to detect all view resolvers
*/
public void setDetectAllViewResolvers(boolean detectAllViewResolvers) {}
/**
* Set whether to throw a NoHandlerFoundException when no Handler was found for this request.
* This exception can then be caught with a HandlerExceptionResolver or an @ExceptionHandler
* controller method. Default is false.
*
* @param throwExceptionIfNoHandlerFound whether to throw exception
*/
public void setThrowExceptionIfNoHandlerFound(boolean throwExceptionIfNoHandlerFound) {}
/**
* Set whether to perform cleanup of request attributes after an include request.
* Default is true.
*
* @param cleanupAfterInclude whether to perform cleanup
*/
public void setCleanupAfterInclude(boolean cleanupAfterInclude) {}
/**
* Process the actual dispatching to the handler.
*
* @param request current HTTP request
* @param response current HTTP response
* @throws Exception in case of any kind of processing failure
*/
protected void doDispatch(HttpServletRequest request, HttpServletResponse response)
throws Exception {}
}Interface for defining a mapping between requests and handler objects.
/**
* Interface to be implemented by objects that define a mapping between
* requests and handler objects.
*
* This interface can be implemented by application developers, although this is not
* necessary, as BeanNameUrlHandlerMapping and RequestMappingHandlerMapping are
* included in the framework. The former is the default if no HandlerMapping bean
* is registered in the application context.
*/
public interface HandlerMapping {
/**
* Name of the HttpServletRequest attribute that contains the mapped handler for the best
* matching pattern.
*/
String BEST_MATCHING_HANDLER_ATTRIBUTE = HandlerMapping.class.getName() + ".bestMatchingHandler";
/**
* Name of the HttpServletRequest attribute that contains the path within the handler mapping,
* in case of a pattern match, or the full relevant URI (typically within the DispatcherServlet's
* mapping) else.
*/
String PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE = HandlerMapping.class.getName() + ".pathWithinHandlerMapping";
/**
* Name of the HttpServletRequest attribute that contains the best matching pattern within
* the handler mapping.
*/
String BEST_MATCHING_PATTERN_ATTRIBUTE = HandlerMapping.class.getName() + ".bestMatchingPattern";
/**
* Name of the HttpServletRequest attribute that contains the URI templates map, mapping
* variable names to values.
*/
String URI_TEMPLATE_VARIABLES_ATTRIBUTE = HandlerMapping.class.getName() + ".uriTemplateVariables";
/**
* Name of the HttpServletRequest attribute that contains a map with URI variable names
* and a corresponding MultiValueMap of URI matrix variables for each.
*/
String MATRIX_VARIABLES_ATTRIBUTE = HandlerMapping.class.getName() + ".matrixVariables";
/**
* Name of the HttpServletRequest attribute that contains the set of producible MediaTypes
* applicable to the mapped handler.
*/
String PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE = HandlerMapping.class.getName() + ".producibleMediaTypes";
/**
* Name of the HttpServletRequest attribute that contains the API version attribute.
*
* @since 7.0
*/
String API_VERSION_ATTRIBUTE = HandlerMapping.class.getName() + ".apiVersion";
/**
* Return a handler and any interceptors for this request. The choice may be made
* on request URL, session state, or any factor the implementing class chooses.
*
* @param request current HTTP request
* @return a HandlerExecutionChain instance containing handler object and any interceptors,
* or null if no mapping found
* @throws Exception if there is an internal error
*/
HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception;
/**
* Whether this HandlerMapping uses parsed PathPatterns (true) or String pattern
* matching with PathMatcher (false).
*
* @return whether parsed patterns are used
* @since 5.3
*/
default boolean usesPathPatterns() {
return false;
}
}Interface that uses a strategy pattern to allow different handler execution strategies.
/**
* MVC framework SPI, allowing parameterization of the core MVC workflow.
*
* Interface that must be implemented for each handler type to handle a request.
* This interface is used to allow the DispatcherServlet to be infinitely extensible.
* The DispatcherServlet accesses all installed handlers through this interface,
* meaning that it does not contain code specific to any handler type.
*/
public interface HandlerAdapter {
/**
* Given a handler instance, return whether or not this HandlerAdapter can
* support it. Typical HandlerAdapters will base the decision on the handler
* type. HandlerAdapters will usually only support one handler type each.
*
* @param handler the handler object to check
* @return whether this object can use the given handler
*/
boolean supports(Object handler);
/**
* Use the given handler to handle this request. The workflow that is required may vary widely.
*
* @param request current HTTP request
* @param response current HTTP response
* @param handler the handler to use
* @return a ModelAndView object with the name of the view and the required model data,
* or null if the request has been handled directly
* @throws Exception in case of errors
*/
ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception;
/**
* Get the last-modified value for the given handler.
*
* @param request current HTTP request
* @param handler the handler to use
* @return the last-modified value for the given handler
* @deprecated as of 5.3.9 along with the deprecated variant of handle
*/
@Deprecated(since = "5.3.9")
long getLastModified(HttpServletRequest request, Object handler);
}Handler execution chain, consisting of a handler object and interceptors.
/**
* Handler execution chain, consisting of handler object and any handler interceptors.
* Returned by HandlerMapping's getHandler method.
*/
public class HandlerExecutionChain {
/**
* Create a new HandlerExecutionChain.
*
* @param handler the handler object to execute
*/
public HandlerExecutionChain(Object handler) {}
/**
* Create a new HandlerExecutionChain.
*
* @param handler the handler object to execute
* @param interceptors the array of interceptors to apply
*/
public HandlerExecutionChain(Object handler, HandlerInterceptor... interceptors) {}
/**
* Return the handler object to execute.
*
* @return the handler object
*/
public Object getHandler() {}
/**
* Add the given interceptor to the end of the interceptor chain.
*
* @param interceptor the interceptor to add
*/
public void addInterceptor(HandlerInterceptor interceptor) {}
/**
* Add the given interceptor at the specified index of the interceptor chain.
*
* @param index the index to add the interceptor at
* @param interceptor the interceptor to add
*/
public void addInterceptor(int index, HandlerInterceptor interceptor) {}
/**
* Add the given interceptors to the end of the interceptor chain.
*
* @param interceptors the array of interceptors to add
*/
public void addInterceptors(HandlerInterceptor... interceptors) {}
/**
* Return the array of interceptors to apply (in the given order).
*
* @return the array of HandlerInterceptors instances (may be null)
*/
public HandlerInterceptor[] getInterceptors() {}
/**
* Return the list of interceptors to apply (in the given order).
*
* @return the list of HandlerInterceptors instances (potentially empty)
*/
public List<HandlerInterceptor> getInterceptorList() {}
/**
* Apply preHandle methods of registered interceptors.
*
* @param request current HTTP request
* @param response current HTTP response
* @return true if the execution chain should proceed with the next interceptor
* or the handler itself. Else, DispatcherServlet assumes that this interceptor
* has already dealt with the response itself
* @throws Exception in case of errors
*/
boolean applyPreHandle(HttpServletRequest request, HttpServletResponse response)
throws Exception {}
/**
* Apply postHandle methods of registered interceptors.
*
* @param request current HTTP request
* @param response current HTTP response
* @param mv the ModelAndView that the handler returned
* @throws Exception in case of errors
*/
void applyPostHandle(HttpServletRequest request, HttpServletResponse response,
ModelAndView mv) throws Exception {}
/**
* Trigger afterCompletion callbacks on the mapped HandlerInterceptors.
* Will just invoke afterCompletion for all interceptors whose preHandle invocation
* has successfully completed and returned true.
*
* @param request current HTTP request
* @param response current HTTP response
* @param ex any exception thrown on handler execution, or null if none
*/
void triggerAfterCompletion(HttpServletRequest request, HttpServletResponse response,
Exception ex) {}
/**
* Apply afterConcurrentHandlingStarted callback on mapped AsyncHandlerInterceptors.
*
* @param request current HTTP request
* @param response current HTTP response
*/
void applyAfterConcurrentHandlingStarted(HttpServletRequest request,
HttpServletResponse response) {}
}Usage Example:
@Configuration
public class CustomMvcConfig {
@Bean
public HandlerMapping customHandlerMapping() {
SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
Map<String, Object> urlMap = new HashMap<>();
urlMap.put("/custom/**", customHandler());
mapping.setUrlMap(urlMap);
mapping.setOrder(Ordered.HIGHEST_PRECEDENCE);
return mapping;
}
@Bean
public HttpRequestHandler customHandler() {
return (request, response) -> {
response.setContentType("text/plain");
response.getWriter().write("Custom handler response");
};
}
}Interface for handling exceptions thrown during handler execution.
public interface HandlerExceptionResolver {
ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response,
Object handler, Exception ex);
}Interface for view name resolution.
public interface ViewResolver {
View resolveViewName(String viewName, Locale locale) throws Exception;
}Strategy for translating an incoming request into a logical view name when no explicit view name is provided.
public interface RequestToViewNameTranslator {
String getViewName(HttpServletRequest request) throws Exception;
}