天天看點

The DispatcherServlet

Spring's web MVC framework is, like many other web MVC frameworks, request-driven, designed around a central servlet that dispatches requests to controllers and offers other functionality facilitating the development of web applications. Spring's DispatcherServlet however, does more than just that. It is completely integrated with the Spring IoC container and as such allows you to use every other feature that Spring has.

The request processing workflow of the Spring Web MVC DispatcherServlet is illustrated in the following diagram. The pattern-savvy reader will recognize that the DispatcherServlet is an expression of the “Front Controller” design pattern (this is a pattern that Spring Web MVC shares with many other leading web frameworks)

The DispatcherServlet

The DispatcherServlet is an actual Servlet (it inherits from the HttpServlet base class), and as such is declared in the web.xml of your web application. Requests that you want the DispatcherServlet to handle will have to be mapped using a URL mapping in the same web.xml file. This is standard J2EE servlet configuration; an example of such a DispatcherServlet declaration and mapping can be found below.

<web-app>

    <servlet>
        <servlet-name>example</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>example</servlet-name>
        <url-pattern>*.form</url-pattern>
    </servlet-mapping>

</web-app>      

In the example above, all requests ending with  .form  will be handled by the  'example'   DispatcherServlet . This is only the first step in setting up Spring Web MVC... the various beans used by the Spring Web MVC framework (over and above the  DispatcherServlet  itself) now need to be configured.