Spring MVC请求处理流程

摘自官方配图:https://docs.spring.io/spring/docs/4.3.16.RELEASE/spring-framework-reference/htmlsingle/#overview-getting-started-with-spring

Figure 22.1. The request processing workflow in Spring Web MVC (high level)

mvc

The DispatcherServlet is an actual Servlet (it inherits from the HttpServlet base class), and as such is declared in your web application. You need to map requests that you want the DispatcherServlet to handle, by using a URL mapping. Here is a standard Java EE Servlet configuration in a Servlet 3.0+ environment:

public class MyWebApplicationInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext container) {
        ServletRegistration.Dynamic registration = container.addServlet("example", new DispatcherServlet());
        registration.setLoadOnStartup(1);
        registration.addMapping("/example/*");
    }
}

In the preceding example, all requests starting with /example will be handled by the DispatcherServlet instance named example.

WebApplicationInitializer is an interface provided by Spring MVC that ensures your code-based configuration is detected and automatically used to initialize any Servlet 3 container. An abstract base class implementation of this interface named AbstractAnnotationConfigDispatcherServletInitializer makes it even easier to register the DispatcherServlet by simply specifying its servlet mapping and listing configuration classes - it’s even the recommended way to set up your Spring MVC application. See Code-based Servlet container initialization for more details.

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. You need to map requests that you want the DispatcherServlet to handle, by using a URL mapping in the same web.xml file. This is standard Java EE Servlet configuration; the following example shows such a DispatcherServlet declaration and mapping:

Below is the web.xml equivalent of the above code based example:

<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>/example/*</url-pattern>
    </servlet-mapping>

</web-app>


猜你喜欢

转载自blog.csdn.net/sjmz30071360/article/details/80179480