Overview of the Spring MVC startup process

Spring MVC is a Java-based web framework that provides an MVC (Model-View-Controller)-based architectural pattern that helps developers build web applications more easily. In this article, we will delve into the startup process and initialization process of Spring MVC.

Key steps

Load configuration file: The configuration file of Spring MVC is generally in XML format, and the configuration file is loaded through ApplicationContext to obtain related beans.

Initialize DispatcherServlet: DispatcherServlet is the core of the entire Spring MVC, it inherits HttpServlet, and implements HTTP requests process and respond. When the DispatcherServlet is initialized, its init() method is called, and some parameters are set for it, such as the location of the SpringMVC configuration file, etc.

Initialize HandlerMapping: HandlerMapping is responsible for mapping requests to corresponding Controllers. DispatcherServlet initializes HandlerMapping during initialization and registers it in its own properties.

Initialize HandlerAdapter: HandlerAdapter is used to convert the request object into a ModelAndView object. During initialization, DispatcherServlet will obtain the corresponding Controller according to the HandlerMapping and generate the corresponding HandlerAdapter.

Initialize ViewResolver: ViewResolver is used to render the ModelAndView object into a specific view (such as JSP, HTML, etc.). During initialization, DispatcherServlet will generate the corresponding ViewResolver object according to the configuration of ViewResolver.

Start Spring MVC: After the initialization of DispatcherServlet is completed, it will listen to HTTP requests and distribute the requests to the corresponding Controller for processing. After the processing is completed, the ModelAndView object is handed over to ViewResolver for rendering.

Spring MVC initialization process

Load configuration file

The configuration file of Spring MVC is generally in XML format and can be configured in web.xml. In the configuration file, you need to declare DispatcherServlet, and specify the location of the Spring MVC configuration file. For example:

<servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring-mvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

A Servlet named dispatcherServlet is configured here and mapped to the “/” path. At the same time, the location of the Spring MVC configuration file is specified as classpath:spring-mvc.xml.

Initialize DispatcherServlet

DispatcherServlet is the core of the entire Spring MVC. It inherits HttpServlet and realizes the processing and response to HTTP requests. When the DispatcherServlet is initialized, its init() method is called and some parameters are set for it, such as the location of the Spring MVC configuration file. For the specific initialization process, please refer to the source code of DispatcherServlet:

public void init(ServletConfig config) throws ServletException {<!-- -->
    //...
    try {<!-- -->
        this. webApplicationContext = initWebApplicationContext();
        initFrameworkServlet();
    }
    catch (ServletException ex) {<!-- -->
        logger. error("Context initialization failed", ex);
        throw ex;
    }
    catch (RuntimeException ex) {<!-- -->
        logger. error("Context initialization failed", ex);
        throw ex;
    }
    //...
}

protected WebApplicationContext initWebApplicationContext() {<!-- -->
    //...
    // Load configuration file, create ApplicationContext
    ConfigurableWebApplicationContext wac = new XmlWebApplicationContext();
    wac.setServletContext(getServletContext());
    wac.setConfigLocation(getConfigLocation());
    //...
    // Set the parent container of DispatcherServlet to ApplicationContext
    wac.setParent(applicationContext);
    //...
    wac. refresh();
    //...
    return wac;
}

It can be seen that the initialization process of DispatcherServlet mainly includes two steps: loading configuration files, creating ApplicationContext, and setting the parent container of DispatcherServlet as ApplicationContext.

Initialize HandlerMapping

HandlerMapping is responsible for mapping the request to the corresponding Controller. DispatcherServlet initializes HandlerMapping and registers it in its own properties when it is initialized. Spring MVC provides a variety of HandlerMapping, including:

BeanNameUrlHandlerMapping: Maps the request URL with the name of the Handler Bean.

SimpleUrlHandlerMapping: Map the request URL to the Handler object.

DefaultAnnotationHandlerMapping: Map classes annotated with @Controller.

RequestMappingHandlerMapping: Map methods annotated with @RequestMapping.

During initialization, DispatcherServlet will generate the corresponding HandlerMapping according to the content in the configuration file, and register it in its own properties. For example:

<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
    <property name="mappings">
        <props>
            <prop key="/hello">helloController</prop>
        </props>
    </property>
</bean>
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>

Three HandlerMappings are configured here: BeanNameUrlHandlerMapping, SimpleUrlHandlerMapping and RequestMappingHandlerMapping.

Initialize HandlerAdapter

HandlerAdapter is used to convert request objects into ModelAndView objects. During initialization, DispatcherServlet will obtain the corresponding Controller according to the HandlerMapping and generate the corresponding HandlerAdapter. Spring MVC provides a variety of HandlerAdapter, including:

SimpleControllerHandlerAdapter: Used to handle Controllers that implement the Controller interface.

HttpRequestHandlerAdapter: Used to handle Controllers that implement the HttpRequestHandler interface.

AnnotationMethodHandlerAdapter: Used to handle methods annotated with @RequestMapping.

During initialization, DispatcherServlet will obtain the corresponding Controller according to the HandlerMapping and generate the corresponding HandlerAdapter. For example:

<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>
<bean class="org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter"/>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>

Three HandlerAdapters are configured here: SimpleControllerHandlerAdapter, HttpRequestHandlerAdapter and AnnotationMethodHandlerAdapter.

Initialize ViewResolver

ViewResolver is used to render ModelAndView objects into specific views (such as JSP, HTML, etc.). During initialization, DispatcherServlet will generate the corresponding ViewResolver object according to the configuration of ViewResolver. Spring MVC provides a variety of ViewResolvers, including:

InternalResourceViewResolver: Resolves view names into JSP files.

VelocityViewResolver: Resolves view names to Velocity template files.

FreeMarkerViewResolver: Resolves view names to FreeMarker template files.

TilesViewResolver: Resolves view names into Tiles view definitions.

During initialization, DispatcherServlet will generate the corresponding ViewResolver object according to the configuration of ViewResolver. For example:

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/views/"/>
    <property name="suffix" value=".jsp"/>
</bean>

An InternalResourceViewResolver object is configured here, which resolves view names into JSP files. For the specific parsing process, please refer to the source code of InternalResourceViewResolver:

public View resolveViewName(String viewName, Locale locale) throws Exception {<!-- -->
    //...
    // Parse the view name to a JSP file
    String resourcePath = this.prefix + viewName + this.suffix;
    //...
    return new InternalResourceView(resourcePath);
}

As can be seen, the resolveViewName method of InternalResourceViewResolver resolves the view name into a JSP file and returns an InternalResourceView object.

Start Spring MVC

After the initialization is complete, DispatcherServlet will listen to HTTP requests and distribute the requests to the corresponding Controller for processing. After the processing is completed, the ModelAndView object is handed over to ViewResolver for rendering. For the specific processing flow, please refer to the source code of DispatcherServlet:

protected void doService(HttpServletRequest request, HttpServletResponse response) throws Exception {<!-- -->
    //...
    // Distribute the request to the corresponding Controller for processing
    HandlerExecutionChain mappedHandler = null;
    boolean multipartRequestParsed = false;
    mappedHandler = getHandler(processedRequest);
    if (mappedHandler == null || mappedHandler.getHandler() == null) {<!-- -->
        noHandlerFound(processedRequest, response);
        return;
    }
    //...
    // Execute the method of Controller and process the request
    mv = ha. handle(processedRequest, response, mappedHandler. getHandler());
    //...
    // Pass the ModelAndView object to ViewResolver for rendering
    render(mv, processedRequest, response);
    //...
}

It can be seen that the doService method of DispatcherServlet will distribute the request to the corresponding Controller for processing. After the processing is completed, the ModelAndView object will be handed over to ViewResolver for rendering.

Today we have a preliminary understanding of the startup process. In the following chapters, we will learn more about the functions of the corresponding types in each step.