SpringMVC learning: SpringMVC and SpringBoot automatically configure SpringMVC

1. SpringMVC execution process

Spring MVC is a lightweight Web development framework based on the MVC design pattern provided by Spring, which is essentially equivalent to Servlet.
Insert image description here

  1. The user clicks on a request path to initiate an HTTP request, which will be submitted to the DispatcherServlet (front-end controller).
  2. DispatcherServlet receives the request and hands it to the processor mapper based on the request information.
  3. The handler mapper (HandlerMapping) finds the Handler matching the url based on the user's url request and returns an execution chain.
  4. DispacherServlet then requests the processor adapter (HandlerAdapter) according to the execution chain.
  5. The processor adapter calls the corresponding handle for processing.
  6. After the corresponding handler completes processing, it returns ModelAndVIew to the processor adapter.
  7. The processor adapter returns the accepted ModelAndView to the DispatcherServlet.
  8. DispatcherServlet requests the view resolver to resolve the view.
  9. After the view parser completes processing, it returns the View object to DispacherServlet.
  10. Finally, the front-end controller performs view rendering on the View (ie, fills the model data into the view).

MVC:
View layer (View): Responsible for formatting data and presenting them to users, including data display, user interaction, data validation, interface design and other functions.

Controller: Responsible for receiving and forwarding requests. After processing the requests, specify the view and send the response results to the client.

Data model layer (Model): The model object has the most processing tasks and is the main part of the application. It is responsible for processing data logic (business rules) and implementing data operations (that is, accessing data in the database).

2. Spring uses MVC

Spring MVC is based on Servlet, and DispatcherServlet is the core of the entire Spring MVC framework. It is mainly responsible for intercepting requests and dispatching them to the corresponding processors for processing. So to configure Spring MVC, you must first define DispatcherServlet. Like all servlets, users must be configured in web.xml.

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">
  <!-- 部署 DispatcherServlet -->
  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:config/springmvc-servlet.xml</param-value>
    </init-param>
    <!-- 表示容器再启动时立即加载servlet -->
    <load-on-startup>1</load-on-startup>
    <!--支持异步处理-->
    <async-supported>true</async-supported>
  </servlet>
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <!-- 处理所有URL -->
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

Create controller

@Controller
public class UserController {
    
    
    @RequestMapping(value = "/user/login")
    public String login() {
    
    
        return "login";
    }
    @RequestMapping(value = "/user/register")
    public String register() {
    
    
        return "register";
    }
}

3. SpringMVC common annotations

@Controller
controller, handles http requests.

@RestController compound annotation
is equivalent to @ResponseBody+@Controller combined. The effect of RestController is to display the object returned by the method directly in json format on the browser.

@RequestBody
reads the Request Body through HttpMessageConverter and deserializes it into an Object (generally speaking) object

@RequestMapping
@RequestMapping is one of the most commonly used annotations in Spring web applications. This annotation will map HTTP requests to MVC and REST controller processing methods.

@GetMapping is a method annotation used to map HTTP get requests to specific handlers.
Annotation abbreviation: @RequestMapping(value = “/say”, method = RequestMethod.GET) is equivalent to: @GetMapping(value = “/say”)

@PostMapping method annotation for mapping HTTP post requests to specific handlers

@PathVariable: Get the data in the url

@RequestParam: Get the value of the request parameter

@RequestHeader binds the value of the Request header part to the parameters of the method

@CookieValue binds the cookie value in the Request header to the method parameters

4. DispatcherServlet function

After using SpringBoot, we can no longer directly see the use of DispatcherServlet.

DispatcherServlet is mainly used for responsibility scheduling work. It is mainly used to control the process. Its main responsibilities are as follows:
file upload parsing. If the request type is multipart, file upload parsing will be performed through MultipartResolver;
through HandlerMapping, the request will be mapped to the processor (returning a HandlerExecutionChain, It includes a processor, multiple HandlerInterceptor interceptors);
supports multiple types of processors (processors in HandlerExecutionChain) through HandlerAdapter;
parses logical view names to specific view implementations through ViewResolver;
localization analysis;
rendering specific views, etc. ;
If an exception is encountered during execution, it will be handed over to HandlerExceptionResolver for resolution.

DispatcherServlet processing flow:
When DispatcherServlet is configured and DispatcherServlet receives the corresponding request, processing begins. The processing flow is as follows:

Find the WebApplicationContext and bind it to a property of the request so that the controller and other processors in the processing chain can use the WebApplicationContext. The default attribute name is DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE.

Bind the localization parser to the request so that processors in the processing chain can perform localization processing when processing the request (preparing data, displaying views, etc.). If localized parsing is not required, just ignore it.

Bind a theme resolver to the request so the view can decide which theme to use. If you don't need the theme, you can ignore it.

If you specify an upload file parser, Spring will check whether an upload file exists for each received request. If so, the request will be encapsulated into a MultipartHttpServletRequest for use by other processors in the processing chain. (See Spring's multipart (fileupload) support for more detailed information)

Find the appropriate processor and execute the execution chain (preprocessor, postprocessor, controller) associated with this processor to prepare model data for the view.

If model data is returned, use the view resolver configured in the WebApplicationContext to display the view, otherwise the view will not be displayed. There are many reasons why the returned data model may be empty. For example, the preprocessor or postprocessor may have intercepted the request. This may be for security reasons, or the request may have already been processed and there is no need to process it again.

5. SpringBoot automatically configures DispatcherServlet

SpringBoot implements automatic assembly through @EnableAutoConfiguration.
@EnableAutoConfiguration in the @SpringBootApplication annotation uses the @Import annotation to import an AutoConfigurationImportSelector.class class. The selectImports method of this class will scan a spring.factories file under our class path (which contains many officially written automatic configuration classes The fully qualified name, the storage path is META-INF/spring.factories), and then returns the names of these classes. Simply put, SpringBoot loads various Config class files that have been written and realizes the reuse and componentization of these JavaConfig configuration files.

There is DispatcherServletAutoConfiguration in the spring.factories file, which means that this class will be loaded when springboot starts. The configuration class DispatcherServletAutoConfiguration can be seen from the annotations above: it automatically configures dispatcherServlet, and there is an internal class in it: DispatcherServletRegistrationConfiguration , this class automatically generates a dispatcherServlet bean object and a bean object used to register dispatcherServlet, DispatcherServletRegistrationBean. The function of this object is: external calls can finally call the addRegistration method in ServletRegistrationBean through the onStartup method of its top-level parent interface ServletContextInitializer: finally Add DispatcherServlet to tomcat context.

Insert image description here

Insert image description here

Guess you like

Origin blog.csdn.net/weixin_42774617/article/details/131838401