Learn Java for Web Development

(Tina Meador) #1

230 CHAPTER 5: Building Java Web Applications with Spring Web MVC


The DispatcherServlet

Like any servlet, DispatcherServlet needs to be configured in web.xml to be able to handle requests.
Configuring and using the DispatcherServlet requires the following:



  1. You have to indicate to the container to load DispatcherServlet and map it to
    URL patterns.

  2. After the DispatcherServlet is loaded, it creates its own
    org.springframework.web.context.WebApplicationContext.

  3. The DispatcherServlet then detects the SpringMVC components from this
    application context, and if not found, it will use the default. These SpringMVC
    components and their defaults will be explained later.

  4. DispatcherServlet then delegates tasks to each of the SpringMVC
    components (or their defaults) depending on the request.


Note DispatcherServlet creates its own WebApplicationContext, which contains the web-specific
components such as Controllers and ViewResolver. This WebApplicationContext is then nested inside
the root WebApplicationContext, which is loaded before the DispatcherServlet is initialized to ensure
that the web components in WebApplicationContext of DispatcherServlet can find their dependencies.

DispatcherServlet, like any other servlet, is declared in the web.xml file of your web application.
You need to map requests that you want DispatcherServlet to handle, by using a URL mapping in
the same web.xml file. Listing 5-34 illustrates a DispatcherServlet declaration and mapping.


Listing 5-34. Declaring and Mapping DispatcherServlet




bookstore
org.springframework.web.servlet.DispatcherServlet
1


bookstore
/bookstore/*


In a Servlet 3.0 and newer environment, you can also use WebApplicationInitializer, an interface
provided by the Spring MVC framework, to configure the servlet container programmatically.
Listing 5-35 illustrates the programmatic equivalent of the previous web.xml example.

Free download pdf