228 CHAPTER 5: Building Java Web Applications with Spring Web MVC
Following from Figure 5-6, the high-level overview of the workflow is as follows:
- The client sends a request to the web container in the form of an HTTP request.
- DispatcherServlet intercepts the request to figure out the appropriate
handler mappings. - With the help of handler mappings thus figured out, the DispatcherServlet
dispatches the request to the appropriate controller. - The controller processes the request and returns the model and view objects
to DispatcherServlet in the form of a ModelAndView instance. - DispatcherServlet then resolves the View (which can be JSP, FreeMarker,
Velocity, and so on) by consulting the ViewResolver object. - The selected view is then rendered back to the client.
DispatcherServlet is the heart of Spring Web MVC framework, but before you dive into
DispatcherServlet, first you must look at ApplicationContext in a web application. As mentioned
earlier, a web application has its own specialized WebApplicationContext that must be loaded before
DispatcherServlet is initialized. When the Spring Web MVC application starts and before the web
application is ready to serve the requests, the WebApplicationContext and DispatcherServlet come
into action, as explained here:
- The servlet container initializes the web application and then triggers the
contextInitialized event, which is listened to by the ContextLoaderListener. - ContextLoaderListener creates the root WebApplicationContext.
- The DispatcherServlet is initialized, creating its own WebApplicationContext
and nesting it inside the root WebApplicationContext. - DispatcherServlet searches for components such as ViewResolvers and
HandlerMappings. If a component is found, it will be initialized; otherwise, the
default for the component is initialized.
You will look at these steps in greater detail in the sections that follow.
WebApplicationContext
In web applications, the ApplicationContext used is called WebApplicationContext, and it
is a specialized ApplicationContext that is aware of the servlet environment. It is the root
ApplicationContext in a web application and must be loaded before DispatcherServlet initializes
to ensure that all of the services such as the data source are available that are required by the web
application. WebApplicationContext is configured in the web.xml file using ContextLoaderListener,
as illustrated in Listing 5-31.