|
||||||||||
PREV CLASS NEXT CLASS | FRAMES NO FRAMES | |||||||||
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD |
java.lang.Object javax.servlet.GenericServlet javax.servlet.http.HttpServlet org.springframework.web.servlet.HttpServletBean org.springframework.web.servlet.FrameworkServlet org.springframework.web.servlet.DispatcherServlet
public class DispatcherServlet
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:
HandlerMapping
implementation - pre-built or provided
as part of an application - to control the routing of requests to handler objects.
Default is BeanNameUrlHandlerMapping
.
HandlerMapping objects can be defined as beans in the servlet's application context,
implementing the HandlerMapping interface, overriding the default HandlerMapping
if present. HandlerMappings can be given any bean name (they are tested by type).
HandlerAdapter
; this allows to use any handler interface.
Default adapters are SimpleControllerHandlerAdapter
and ThrowawayControllerHandlerAdapter
,
for Spring's Controller
and
ThrowawayController
interfaces,
respectively. HandlerAdapter objects can be added as beans in the application context,
overriding the default HandlerAdapters. Like HandlerMappings, HandlerAdapters
can be given any bean name (they are tested by type).
HandlerExceptionResolver
, for example mapping certain exceptions to
error pages. Default is none. Additional HandlerExceptionResolvers can be added
through the application context. HandlerExceptionResolver can be given any
bean name (they are tested by type).
ViewResolver
implementation, resolving symbolic view names into View objects. Default is
InternalResourceViewResolver
.
ViewResolver objects can be added as beans in the application context,
overriding the default ViewResolver. ViewResolvers can be given any bean name
(they are tested by type).
MultipartResolver
implementation.
Implementations for Jakarta Commons FileUpload and Jason Hunter's COS are
included; the typical choise is
CommonsMultipartResolver
.
The MultipartResolver bean name is "multipartResolver"; default is none.
LocaleResolver
.
Out-of-the-box implementations work via HTTP accept header, cookie, or session.
The LocaleResolver bean name is "localeResolver"; default is
AcceptHeaderLocaleResolver
.
ThemeResolver
.
Implementations for a fixed theme and for cookie and session storage are included.
The ThemeResolver bean name is "themeResolver"; default is
FixedThemeResolver
.
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 ContextLoaderListener
,
if any, will be shared.
This class and the MVC approach it delivers is discussed in Chapter 12 of Expert One-On-One J2EE Design and Development by Rod Johnson (Wrox, 2002). Note that it is called ControllerServlet there; it has been renamed since to emphasize its dispatching role and avoid confusion with Controller objects that the DispatcherServlet will dispatch to.
Controller
,
ContextLoaderListener
,
Serialized FormField Summary | |
---|---|
static String |
HANDLER_ADAPTER_BEAN_NAME
Well-known name for the HandlerAdapter object in the bean factory for this namespace. |
static String |
HANDLER_EXCEPTION_RESOLVER_BEAN_NAME
Well-known name for the HandlerExceptionResolver object in the bean factory for this namespace. |
static String |
HANDLER_EXECUTION_CHAIN_ATTRIBUTE
Request attribute to hold the currently chosen HandlerExecutionChain. |
static String |
HANDLER_MAPPING_BEAN_NAME
Well-known name for the HandlerMapping object in the bean factory for this namespace. |
static String |
LOCALE_RESOLVER_ATTRIBUTE
Request attribute to hold the current LocaleResolver, retrievable by views. |
static String |
LOCALE_RESOLVER_BEAN_NAME
Well-known name for the LocaleResolver object in the bean factory for this namespace. |
static String |
MULTIPART_RESOLVER_ATTRIBUTE
Request attribute to hold current multipart resolver, retrievable by views/binders. |
static String |
MULTIPART_RESOLVER_BEAN_NAME
Well-known name for the MultipartResolver object in the bean factory for this namespace. |
static String |
PAGE_NOT_FOUND_LOG_CATEGORY
Log category to use when no mapped handler is found for a request. |
protected static Log |
pageNotFoundLogger
Additional logger to use when no mapped handler is found for a request. |
static String |
THEME_RESOLVER_ATTRIBUTE
Request attribute to hold the current ThemeResolver, retrievable by views. |
static String |
THEME_RESOLVER_BEAN_NAME
Well-known name for the ThemeResolver object in the bean factory for this namespace. |
static String |
VIEW_RESOLVER_BEAN_NAME
Well-known name for the ViewResolver object in the bean factory for this namespace. |
static String |
WEB_APPLICATION_CONTEXT_ATTRIBUTE
Request attribute to hold the current web application context. |
Fields inherited from class org.springframework.web.servlet.FrameworkServlet |
---|
DEFAULT_CONTEXT_CLASS, DEFAULT_NAMESPACE_SUFFIX, SERVLET_CONTEXT_PREFIX |
Fields inherited from class org.springframework.web.servlet.HttpServletBean |
---|
logger |
Constructor Summary | |
---|---|
DispatcherServlet()
|
Method Summary | |
---|---|
protected LocaleContext |
buildLocaleContext(HttpServletRequest request)
Build a LocaleContext for the given request, exposing the request's primary locale as current locale. |
protected HttpServletRequest |
checkMultipart(HttpServletRequest request)
Convert the request into a multipart request, and make multipart resolver available. |
protected void |
doDispatch(HttpServletRequest request,
HttpServletResponse response)
Process the actual dispatching to the handler. |
protected void |
doService(HttpServletRequest request,
HttpServletResponse response)
Exposes the DispatcherServlet-specific request attributes and delegates to doDispatch(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) for the actual dispatching. |
protected List |
getDefaultStrategies(Class strategyInterface)
Create a List of default strategy objects for the given strategy interface. |
protected Object |
getDefaultStrategy(Class strategyInterface)
Return the default strategy object for the given strategy interface. |
protected HandlerExecutionChain |
getHandler(HttpServletRequest request,
boolean cache)
Return the HandlerExecutionChain for this request. |
protected HandlerAdapter |
getHandlerAdapter(Object handler)
Return the HandlerAdapter for this handler object. |
protected long |
getLastModified(HttpServletRequest request)
Override HttpServlet's getLastModified method to evaluate
the Last-Modified value of the mapped handler. |
protected void |
initFrameworkServlet()
Overridden method, invoked after any bean properties have been set and the WebApplicationContext and BeanFactory for this namespace is available. |
protected void |
noHandlerFound(HttpServletRequest request,
HttpServletResponse response)
No handler found -> set appropriate HTTP response status. |
protected ModelAndView |
processHandlerException(HttpServletRequest request,
HttpServletResponse response,
Object handler,
Exception ex)
Determine an error ModelAndView via the registered HandlerExceptionResolvers. |
protected void |
render(ModelAndView mv,
HttpServletRequest request,
HttpServletResponse response)
Render the given ModelAndView. |
protected View |
resolveViewName(String viewName,
Map model,
Locale locale,
HttpServletRequest request)
Resolve the given view name into a View object (to be rendered). |
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. |
void |
setDetectAllHandlerAdapters(boolean detectAllHandlerAdapters)
Set whether to detect all HandlerAdapter beans in this servlet's context. |
void |
setDetectAllHandlerExceptionResolvers(boolean detectAllHandlerExceptionResolvers)
Set whether to detect all HandlerExceptionResolver beans in this servlet's context. |
void |
setDetectAllHandlerMappings(boolean detectAllHandlerMappings)
Set whether to detect all HandlerMapping beans in this servlet's context. |
void |
setDetectAllViewResolvers(boolean detectAllViewResolvers)
Set whether to detect all ViewResolver beans in this servlet's context. |
void |
setThreadContextInheritable(boolean threadContextInheritable)
Set whether to expose the LocaleContext as inheritable for child threads (using an InheritableThreadLocal ). |
Methods inherited from class org.springframework.web.servlet.FrameworkServlet |
---|
createWebApplicationContext, destroy, doDelete, doGet, doPost, doPut, getContextClass, getContextConfigLocation, getNamespace, getServletContextAttributeName, getUsernameForRequest, getWebApplicationContext, initServletBean, initWebApplicationContext, isPublishContext, isPublishEvents, processRequest, setContextClass, setContextConfigLocation, setNamespace, setPublishContext, setPublishEvents |
Methods inherited from class org.springframework.web.servlet.HttpServletBean |
---|
addRequiredProperty, getServletContext, getServletName, init, initBeanWrapper |
Methods inherited from class javax.servlet.http.HttpServlet |
---|
doHead, doOptions, doTrace, service, service |
Methods inherited from class javax.servlet.GenericServlet |
---|
getInitParameter, getInitParameterNames, getServletConfig, getServletInfo, init, log, log |
Methods inherited from class java.lang.Object |
---|
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
Field Detail |
---|
public static final String MULTIPART_RESOLVER_BEAN_NAME
public static final String LOCALE_RESOLVER_BEAN_NAME
public static final String THEME_RESOLVER_BEAN_NAME
public static final String HANDLER_MAPPING_BEAN_NAME
public static final String HANDLER_ADAPTER_BEAN_NAME
public static final String HANDLER_EXCEPTION_RESOLVER_BEAN_NAME
public static final String VIEW_RESOLVER_BEAN_NAME
public static final String HANDLER_EXECUTION_CHAIN_ATTRIBUTE
public static final String WEB_APPLICATION_CONTEXT_ATTRIBUTE
public static final String MULTIPART_RESOLVER_ATTRIBUTE
public static final String LOCALE_RESOLVER_ATTRIBUTE
public static final String THEME_RESOLVER_ATTRIBUTE
public static final String PAGE_NOT_FOUND_LOG_CATEGORY
protected static final Log pageNotFoundLogger
Constructor Detail |
---|
public DispatcherServlet()
Method Detail |
---|
public void setDetectAllHandlerMappings(boolean detectAllHandlerMappings)
Default is "true". Turn this off if you want this servlet to use a single HandlerMapping, despite multiple HandlerMapping beans being defined in the context.
public void setDetectAllHandlerAdapters(boolean detectAllHandlerAdapters)
Default is "true". Turn this off if you want this servlet to use a single HandlerAdapter, despite multiple HandlerAdapter beans being defined in the context.
public void setDetectAllHandlerExceptionResolvers(boolean detectAllHandlerExceptionResolvers)
Default is "true". Turn this off if you want this servlet to use a single HandlerExceptionResolver, despite multiple HandlerExceptionResolver beans being defined in the context.
public void setDetectAllViewResolvers(boolean detectAllViewResolvers)
Default is "true". Turn this off if you want this servlet to use a single ViewResolver, despite multiple ViewResolver beans being defined in the context.
public void setCleanupAfterInclude(boolean cleanupAfterInclude)
Default is "true", which is strongly recommended. Views should not rely on request attributes having been set by (dynamic) includes. This allows JSP views rendered by an included controller to use any model attributes, even with the same names as in the main JSP, without causing side effects. Only turn this off for special needs, for example to deliberately allow main JSPs to access attributes from JSP views rendered by an included controller.
public void setThreadContextInheritable(boolean threadContextInheritable)
InheritableThreadLocal
).
Default is "false", to avoid side effects on spawned background threads. Switch this to "true" to enable inheritance for custom child threads which are spawned during request processing and only used for this request (that is, ending after their initial task, without reuse of the thread).
WARNING: Do not use inheritance for child threads if you are
accessing a thread pool which is configured to potentially add new threads
on demand (e.g. a JDK ThreadPoolExecutor
),
since this will expose the inherited context to such a pooled thread.
protected void initFrameworkServlet() throws ServletException, BeansException
Loads HandlerMapping and HandlerAdapter objects, and configures a ViewResolver and a LocaleResolver.
initFrameworkServlet
in class FrameworkServlet
ServletException
- in case of an initialization exception
BeansException
- if thrown by ApplicationContext methodsprotected Object getDefaultStrategy(Class strategyInterface) throws BeansException
The default implementation delegates to getDefaultStrategies(java.lang.Class)
,
expecting a single object in the list.
strategyInterface
- the strategy interface
BeansException
- if initialization failedgetDefaultStrategies(java.lang.Class)
protected List getDefaultStrategies(Class strategyInterface) throws BeansException
The default implementation uses the "DispatcherServlet.properties" file (in the same package as the DispatcherServlet class) to determine the class names. It instantiates the strategy objects and satisifies ApplicationContextAware if necessary.
strategyInterface
- the strategy interface
BeansException
- if initialization failedprotected void doService(HttpServletRequest request, HttpServletResponse response) throws Exception
doDispatch(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
for the actual dispatching.
doService
in class FrameworkServlet
request
- current HTTP requestresponse
- current HTTP response
Exception
- in case of any kind of processing failureHttpServlet.doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
,
HttpServlet.doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception
The handler will be obtained by applying the servlet's HandlerMappings in order. The HandlerAdapter will be obtained by querying the servlet's installed HandlerAdapters to find the first that supports the handler class.
All HTTP methods are handled by this method. It's up to HandlerAdapters or handlers themselves to decide which methods are acceptable.
request
- current HTTP requestresponse
- current HTTP response
Exception
- in case of any kind of processing failureprotected long getLastModified(HttpServletRequest request)
getLastModified
method to evaluate
the Last-Modified value of the mapped handler.
getLastModified
in class HttpServlet
protected LocaleContext buildLocaleContext(HttpServletRequest request)
The default implementation uses the dispatcher's LocaleResolver to obtain the current locale, which might change during a request.
request
- current HTTP request
protected HttpServletRequest checkMultipart(HttpServletRequest request) throws MultipartException
request
- current HTTP request
MultipartException
MultipartResolver.resolveMultipart(javax.servlet.http.HttpServletRequest)
protected HandlerExecutionChain getHandler(HttpServletRequest request, boolean cache) throws Exception
request
- current HTTP requestcache
- whether to cache the HandlerExecutionChain in a request attribute
null
if no handler could be found
Exception
protected void noHandlerFound(HttpServletRequest request, HttpServletResponse response) throws IOException
request
- current HTTP requestresponse
- current HTTP response
IOException
- if thrown by the HttpServletResponseprotected HandlerAdapter getHandlerAdapter(Object handler) throws ServletException
handler
- the handler object to find an adapter for
ServletException
- if no HandlerAdapter can be found for the handler.
This is a fatal error.protected ModelAndView processHandlerException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception
request
- current HTTP requestresponse
- current HTTP responsehandler
- the executed handler, or null
if none chosen at the time of
the exception (for example, if multipart resolution failed)ex
- the exception that got thrown during handler execution
Exception
- if no error ModelAndView foundprotected void render(ModelAndView mv, HttpServletRequest request, HttpServletResponse response) throws Exception
mv
- the ModelAndView to renderrequest
- current HTTP servlet requestresponse
- current HTTP servlet response
Exception
- if there's a problem rendering the viewprotected View resolveViewName(String viewName, Map model, Locale locale, HttpServletRequest request) throws Exception
Default implementations asks all ViewResolvers of this dispatcher. Can be overridden for custom resolution strategies, potentially based on specific model attributes or request parameters.
viewName
- the name of the view to resolvemodel
- the model to be passed to the viewlocale
- the current localerequest
- current HTTP servlet request
null
if none found
Exception
- if the view cannot be resolved
(typically in case of problems creating an actual View object)ViewResolver.resolveViewName(java.lang.String, java.util.Locale)
|
||||||||||
PREV CLASS NEXT CLASS | FRAMES NO FRAMES | |||||||||
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD |