Role of DispatcherServlet And WebApplicationContext in Spring MVC
As we all know Spring MVC framework is request driven. DispatcherServlet plays a major role in spring MVC framework. In spring MVC its an expression of “Front Controller” design pattern.
DispatcherServlet is a simple servlet which gets defined in web.xml
DispatcherServlet –> extends –> abstract FrameworkServlet –> extends –> abstract HttpServletBean –> extends –> javax.servlet.http.HttpServlet
Role and Feature of DispactherServlet
- Request comes from web and the first point of contact is DispatcherServlet.
- The DispatcherServlet’s job is to send the request on to a Spring MVC controller.
- When a request comes in DispactherServlet will search for WebApplicationContext and set it to
DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE so that other components can use it.
- LocalResolver, theme resolver and other resolvers will be included in the request for other components.
- Dispatcher servlet will look for handler of this request. If handler is found the request will passed to (or control) pre-processor (if present), controller and post-processor (if present) to prepare the model.
- Model is returned to DisptacherServlet which will render the view.
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. Each DispatcherServlet has its own WebApplicationContext which define all the required beans required for a web application. These can be configured, if not, WebApplicationContext will use default values.
Here are the special beans with default values.
|Bean Type||Description||Default Value|
|HandlerMapping||It maps incoming request to handlers and a list of pre- nad post-processing||BeanNameUrlHandlerMapping and DefaultAnnotationHandlerMapping|
|HandlerAdapter||Helps the DispatchServlet to invoke handler napped to request.||HttpRequestHandlerAdapter and SimpleControllerHandlerAdapter|
|HandlerExceptionResolver||Helps in mapping certain exceptions to error pages or allowing more complex exception handling code.||AnnotationMethodHandlerExceptionResolver, ResponseStatusExceptionResolver, and DefaultHandlerExceptionResolver|
|ViewResolver||Resolving symbolic view names into View objects||InternalResourceViewResolver|
|LocaleResolver||Resolves the locale a client is using, in order to be able to offer internationalized views||AcceptHeaderLocaleResolver|
|ThemeResolver||Resolves themes your web application can use, for example, to offer personalized layouts||FixedThemeResolver|
|MultipartResolver||Parses multi-part requests for example to support processing file uploads from HTML forms.||CommonsMultipartResolver|
All above bean can be customized. It’s the role of WebApplicationContext to supply values to all the beans.