The Spring Framework

org.springframework.web.servlet
Class DispatcherServlet

java.lang.Object
  extended by javax.servlet.GenericServlet
      extended by javax.servlet.http.HttpServlet
          extended by org.springframework.web.servlet.HttpServletBean
              extended by org.springframework.web.servlet.FrameworkServlet
                  extended by org.springframework.web.servlet.DispatcherServlet
All Implemented Interfaces:
Serializable, Servlet, ServletConfig

public class DispatcherServlet
extends FrameworkServlet

Central dispatcher for use within the web MVC framework, e.g. for web UI controllers or HTTP-based remote service exporters. Dispatches to registered handlers for processing a web request.

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:

A web application can use any number of DispatcherServlets. Each servlet will operate in its own namespace. Only the root application context 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.

Author:
Rod Johnson, Juergen Hoeller, Rob Harrop
See Also:
ContextLoaderListener, HandlerMapping, BeanNameUrlHandlerMapping, HandlerAdapter, SimpleControllerHandlerAdapter, Controller, HandlerExceptionResolver, SimpleMappingExceptionResolver, ViewResolver, InternalResourceViewResolver, RequestToViewNameTranslator, DefaultRequestToViewNameTranslator, MultipartResolver, CommonsMultipartResolver, LocaleResolver, AcceptHeaderLocaleResolver, ThemeResolver, FixedThemeResolver, Serialized Form

Field 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_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 REQUEST_TO_VIEW_NAME_TRANSLATOR_BEAN_NAME
          Well-known name for the RequestToViewNameTranslator object in the bean factory for this namespace.
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 THEME_SOURCE_ATTRIBUTE
          Request attribute to hold the current ThemeSource, retrievable by views.
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  HttpServletRequest checkMultipart(HttpServletRequest request)
          Convert the request into a multipart request, and make multipart resolver available.
protected  Object createDefaultStrategy(Class clazz)
          Create a default strategy.
protected  void doDispatch(HttpServletRequest request, HttpServletResponse response)
          Process the actual dispatching to the handler.
protected  void doService(HttpServletRequest request, HttpServletResponse response)
          Expose the DispatcherServlet-specific request attributes and delegate to doDispatch 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  String getDefaultViewName(HttpServletRequest request)
          Translate the supplied request into a default view name.
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.
 ThemeSource getThemeSource()
          Return this servlet's ThemeSource, if any; else return null.
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, i.e. 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.
 
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

MULTIPART_RESOLVER_BEAN_NAME

public static final String MULTIPART_RESOLVER_BEAN_NAME
Well-known name for the MultipartResolver object in the bean factory for this namespace.

See Also:
Constant Field Values

LOCALE_RESOLVER_BEAN_NAME

public static final String LOCALE_RESOLVER_BEAN_NAME
Well-known name for the LocaleResolver object in the bean factory for this namespace.

See Also:
Constant Field Values

THEME_RESOLVER_BEAN_NAME

public static final String THEME_RESOLVER_BEAN_NAME
Well-known name for the ThemeResolver object in the bean factory for this namespace.

See Also:
Constant Field Values

HANDLER_MAPPING_BEAN_NAME

public static final String HANDLER_MAPPING_BEAN_NAME
Well-known name for the HandlerMapping object in the bean factory for this namespace. Only used when "detectAllHandlerMappings" is turned off.

See Also:
setDetectAllHandlerMappings(boolean), Constant Field Values

HANDLER_ADAPTER_BEAN_NAME

public static final String HANDLER_ADAPTER_BEAN_NAME
Well-known name for the HandlerAdapter object in the bean factory for this namespace. Only used when "detectAllHandlerAdapters" is turned off.

See Also:
setDetectAllHandlerAdapters(boolean), Constant Field Values

HANDLER_EXCEPTION_RESOLVER_BEAN_NAME

public static final String HANDLER_EXCEPTION_RESOLVER_BEAN_NAME
Well-known name for the HandlerExceptionResolver object in the bean factory for this namespace. Only used when "detectAllHandlerExceptionResolvers" is turned off.

See Also:
setDetectAllHandlerExceptionResolvers(boolean), Constant Field Values

REQUEST_TO_VIEW_NAME_TRANSLATOR_BEAN_NAME

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.

See Also:
Constant Field Values

VIEW_RESOLVER_BEAN_NAME

public static final String VIEW_RESOLVER_BEAN_NAME
Well-known name for the ViewResolver object in the bean factory for this namespace. Only used when "detectAllViewResolvers" is turned off.

See Also:
setDetectAllViewResolvers(boolean), Constant Field Values

HANDLER_EXECUTION_CHAIN_ATTRIBUTE

public static final String HANDLER_EXECUTION_CHAIN_ATTRIBUTE
Request attribute to hold the currently chosen HandlerExecutionChain. Only used for internal optimizations.


WEB_APPLICATION_CONTEXT_ATTRIBUTE

public static final String WEB_APPLICATION_CONTEXT_ATTRIBUTE
Request attribute to hold the current web application context. Otherwise only the global web app context is obtainable by tags etc.

See Also:
RequestContextUtils.getWebApplicationContext(javax.servlet.ServletRequest)

LOCALE_RESOLVER_ATTRIBUTE

public static final String LOCALE_RESOLVER_ATTRIBUTE
Request attribute to hold the current LocaleResolver, retrievable by views.

See Also:
RequestContextUtils.getLocaleResolver(javax.servlet.http.HttpServletRequest)

THEME_RESOLVER_ATTRIBUTE

public static final String THEME_RESOLVER_ATTRIBUTE
Request attribute to hold the current ThemeResolver, retrievable by views.

See Also:
RequestContextUtils.getThemeResolver(javax.servlet.http.HttpServletRequest)

THEME_SOURCE_ATTRIBUTE

public static final String THEME_SOURCE_ATTRIBUTE
Request attribute to hold the current ThemeSource, retrievable by views.

See Also:
RequestContextUtils.getThemeSource(javax.servlet.http.HttpServletRequest)

PAGE_NOT_FOUND_LOG_CATEGORY

public static final String PAGE_NOT_FOUND_LOG_CATEGORY
Log category to use when no mapped handler is found for a request.

See Also:
Constant Field Values

pageNotFoundLogger

protected static final Log pageNotFoundLogger
Additional logger to use when no mapped handler is found for a request.

Constructor Detail

DispatcherServlet

public DispatcherServlet()
Method Detail

setDetectAllHandlerMappings

public void setDetectAllHandlerMappings(boolean detectAllHandlerMappings)
Set whether to detect all HandlerMapping beans in this servlet's context. Else, just a single bean with name "handlerMapping" will be expected.

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.


setDetectAllHandlerAdapters

public void setDetectAllHandlerAdapters(boolean detectAllHandlerAdapters)
Set whether to detect all HandlerAdapter beans in this servlet's context. Else, just a single bean with name "handlerAdapter" will be expected.

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.


setDetectAllHandlerExceptionResolvers

public void setDetectAllHandlerExceptionResolvers(boolean detectAllHandlerExceptionResolvers)
Set whether to detect all HandlerExceptionResolver beans in this servlet's context. Else, just a single bean with name "handlerExceptionResolver" will be expected.

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.


setDetectAllViewResolvers

public void setDetectAllViewResolvers(boolean detectAllViewResolvers)
Set whether to detect all ViewResolver beans in this servlet's context. Else, just a single bean with name "viewResolver" will be expected.

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.


setCleanupAfterInclude

public void setCleanupAfterInclude(boolean cleanupAfterInclude)
Set whether to perform cleanup of request attributes after an include request, i.e. whether to reset the original state of all request attributes after the DispatcherServlet has processed within an include request. Else, just the DispatcherServlet's own request attributes will be reset, but not model attributes for JSPs or special attributes set by views (for example, JSTL's).

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.


initFrameworkServlet

protected void initFrameworkServlet()
                             throws ServletException,
                                    BeansException
Overridden method, invoked after any bean properties have been set and the WebApplicationContext and BeanFactory for this namespace is available.

Loads HandlerMapping and HandlerAdapter objects, and configures a ViewResolver and a LocaleResolver.

Overrides:
initFrameworkServlet in class FrameworkServlet
Throws:
ServletException - in case of an initialization exception
BeansException - if thrown by ApplicationContext methods

getThemeSource

public ThemeSource getThemeSource()
Return this servlet's ThemeSource, if any; else return null.

Default is to return the WebApplicationContext as ThemeSource, provided that it implements the ThemeSource interface.

See Also:
FrameworkServlet.getWebApplicationContext()

getDefaultStrategy

protected Object getDefaultStrategy(Class strategyInterface)
                             throws BeansException
Return the default strategy object for the given strategy interface.

Default implementation delegates to getDefaultStrategies, expecting a single object in the list.

Parameters:
strategyInterface - the strategy interface
Returns:
the corresponding strategy object
Throws:
BeansException - if initialization failed
See Also:
getDefaultStrategies(java.lang.Class)

getDefaultStrategies

protected List getDefaultStrategies(Class strategyInterface)
                             throws BeansException
Create a List of default strategy objects for the given strategy interface.

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 through the context's BeanFactory.

Parameters:
strategyInterface - the strategy interface
Returns:
the List of corresponding strategy objects
Throws:
BeansException - if initialization failed

createDefaultStrategy

protected Object createDefaultStrategy(Class clazz)
                                throws BeansException
Create a default strategy. Default implementation uses AutowireCapableBeanFactory.createBean.

Parameters:
clazz - the strategy implementation class to instantiate
Returns:
the fully configured strategy instance
Throws:
BeansException - if initialization failed
See Also:
FrameworkServlet.getWebApplicationContext(), ApplicationContext.getAutowireCapableBeanFactory(), AutowireCapableBeanFactory.createBean(java.lang.Class, int, boolean)

doService

protected void doService(HttpServletRequest request,
                         HttpServletResponse response)
                  throws Exception
Expose the DispatcherServlet-specific request attributes and delegate to doDispatch for the actual dispatching.

Specified by:
doService in class FrameworkServlet
Parameters:
request - current HTTP request
response - current HTTP response
Throws:
Exception - in case of any kind of processing failure
See Also:
doDispatch(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)

doDispatch

protected void doDispatch(HttpServletRequest request,
                          HttpServletResponse response)
                   throws Exception
Process the actual dispatching to the handler.

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.

Parameters:
request - current HTTP request
response - current HTTP response
Throws:
Exception - in case of any kind of processing failure

getLastModified

protected long getLastModified(HttpServletRequest request)
Override HttpServlet's getLastModified method to evaluate the Last-Modified value of the mapped handler.

Overrides:
getLastModified in class HttpServlet

checkMultipart

protected HttpServletRequest checkMultipart(HttpServletRequest request)
                                     throws MultipartException
Convert the request into a multipart request, and make multipart resolver available. If no multipart resolver is set, simply use the existing request.

Parameters:
request - current HTTP request
Returns:
the processed request (multipart wrapper if necessary)
Throws:
MultipartException

getHandler

protected HandlerExecutionChain getHandler(HttpServletRequest request,
                                           boolean cache)
                                    throws Exception
Return the HandlerExecutionChain for this request. Try all handler mappings in order.

Parameters:
request - current HTTP request
cache - whether to cache the HandlerExecutionChain in a request attribute
Returns:
the HandlerExceutionChain, or null if no handler could be found
Throws:
Exception

noHandlerFound

protected void noHandlerFound(HttpServletRequest request,
                              HttpServletResponse response)
                       throws IOException
No handler found -> set appropriate HTTP response status.

Parameters:
request - current HTTP request
response - current HTTP response
Throws:
IOException - if thrown by the HttpServletResponse

getHandlerAdapter

protected HandlerAdapter getHandlerAdapter(Object handler)
                                    throws ServletException
Return the HandlerAdapter for this handler object.

Parameters:
handler - the handler object to find an adapter for
Throws:
ServletException - if no HandlerAdapter can be found for the handler. This is a fatal error.

processHandlerException

protected ModelAndView processHandlerException(HttpServletRequest request,
                                               HttpServletResponse response,
                                               Object handler,
                                               Exception ex)
                                        throws Exception
Determine an error ModelAndView via the registered HandlerExceptionResolvers.

Parameters:
request - current HTTP request
response - current HTTP response
handler - 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
Returns:
a corresponding ModelAndView to forward to
Throws:
Exception - if no error ModelAndView found

render

protected void render(ModelAndView mv,
                      HttpServletRequest request,
                      HttpServletResponse response)
               throws Exception
Render the given ModelAndView. This is the last stage in handling a request. It may involve resolving the view by name.

Parameters:
mv - the ModelAndView to render
request - current HTTP servlet request
response - current HTTP servlet response
Throws:
Exception - if there's a problem rendering the view

getDefaultViewName

protected String getDefaultViewName(HttpServletRequest request)
                             throws Exception
Translate the supplied request into a default view name.

Parameters:
request - current HTTP servlet request
Returns:
the view name
Throws:
Exception - if view name translation failed

resolveViewName

protected View resolveViewName(String viewName,
                               Map model,
                               Locale locale,
                               HttpServletRequest request)
                        throws Exception
Resolve the given view name into a View object (to be rendered).

Default implementations asks all ViewResolvers of this dispatcher. Can be overridden for custom resolution strategies, potentially based on specific model attributes or request parameters.

Parameters:
viewName - the name of the view to resolve
model - the model to be passed to the view
locale - the current locale
request - current HTTP servlet request
Returns:
the View object, or null if none found
Throws:
Exception - if the view cannot be resolved (typically in case of problems creating an actual View object)
See Also:
ViewResolver.resolveViewName(java.lang.String, java.util.Locale)

The Spring Framework

Copyright © 2002-2006 The Spring Framework.