Basic understanding and operation of Spring MVC

SpringMVC是隶属于Spring框架的一部分,主要是用来进行Web开发,是对Servlet进行了封装。

First introduce three concepts:

  • SpringMVC is a framework at the Web layer, so its main function is to receive requests and data from the front end, process them, and respond to the processing results to the front end.
  • REST is a software architectural style that reduces development complexity and improves system scalability.
  • SSM integration is the integration of SpringMVC+Spring+Mybatis to complete business development, and it is a comprehensive application of these three frameworks.

Introduction to Spring MVC

SpringMVC:表现层框架技术,主要实现表现层的功能开发

  • The main functions of SpringMVC:
  1. How the controller receives requests and data
  2. How to forward requests and data to the business layer
  3. How to convert the response data into json and send it back to the front end
  • SpringMVC is a web framework, which is to replace Servlet, so let's review the Servlet development process first

1. Create web project (Maven structure)
2. Set up tomcat server, load web project (tomcat plug-in)
3. Import coordinates (Servlet)
4. Define functional class for processing requests (UserServlet)
5. Set request mapping (configuration mapping relationship)

SpringMVC operation steps

  • The production process of SpringMVC is almost the same as the above process, and the operation steps are as follows

1. Create web project (Maven structure)
2. Set tomcat server, load web project (tomcat plug-in)
3. Import coordinates (SpringMVC+Servlet)

<!--1. 导入SpringMVC与servlet的坐标-->
 <dependencies>
   <dependency>
     <groupId>javax.servlet</groupId>
     <artifactId>javax.servlet-api</artifactId>
     <version>3.1.0</version>
     <scope>provided</scope>
   </dependency>
   <dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-webmvc</artifactId>
     <version>5.2.10.RELEASE</version>
   </dependency>
 </dependencies>

4. Define the functional class that handles the request (UserController)
5.Set request mapping (configuration mapping relationship)

//springmvc配置类,本质上还是一个spring配置类
@Configuration
@ComponentScan("com.taro.controller")
public class SpringMvcConfig {
     
     }
//定义表现层控制器bean
@Controller
public class UserController {
     
     

   //设置映射路径为/save,即外部访问路径
   @RequestMapping("/save")
   //设置当前操作返回结果为指定json数据(本质上是一个字符串信息)
   @ResponseBody
   public String save(){
     
     
       System.out.println("user save ...");
       return "{'info':'springmvc'}";
   }

   //设置映射路径为/delete,即外部访问路径
   @RequestMapping("/delete")
   @ResponseBody
   public String delete(){
     
     
       System.out.println("user save ...");
      return "{'info':'springmvc'}";
   }
}

6.Load SpringMVC settings into the Tomcat container

//web容器配置类
public class ServletContainersInitConfig extends > > >AbstractDispatcherServletInitializer {
     
     
   //加载springmvc配置类,产生springmvc容器(本质还是spring容器)
   protected WebApplicationContext createServletApplicationContext() {
     
     
       //初始化WebApplicationContext对象
      AnnotationConfigWebApplicationContext ctx = new >AnnotationConfigWebApplicationContext();
       //加载指定配置类
       ctx.register(SpringMvcConfig.class);
       return ctx;
   }

  //设置由springmvc控制器处理的请求映射路径
   protected String[] getServletMappings() {
     
     
       return new String[]{
     
     "/"};
   }

   //加载spring配置类
   protected WebApplicationContext createRootApplicationContext() {
     
     
       return null;
   }
}

Spring web development must import this package, even if it is not Spring MVC, as long as it is web.
web development must

Precautions

  • spring-webmvcSpringMVC is based on Spring. The reason why only jar packages are imported in pom.xml is that it will automatically depend on spring-related coordinates.
  • The AbstractDispatcherServletInitializer class is an abstract class provided by SpringMVC to quickly initialize the Web3.0 container
    • AbstractDispatcherServletInitializer provides three interface methods for users to implement
  • The createServletApplicationContext method, when creating a Servlet container, loads the bean corresponding to SpringMVC and puts it into the scope of the WebApplicationContext object, and the scope of the WebApplicationContext is the scope of the ServletContext, that is, the scope of the entire web container
  • The getServletMappings method sets the request mapping path corresponding to SpringMVC, that is, which requests are intercepted by SpringMVC
  • createRootApplicationContext method, if you need to load non-SpringMVC corresponding beans when creating a Servlet container, use the current method, and use the same method as createServletApplicationContext.
  • createServletApplicationContext is used to load the SpringMVC environment
  • createRootApplicationContext is used to load the Spring environment
//web容器配置类
public class ServletContainersInitConfig extends AbstractDispatcherServletInitializer {
    
    
    //加载springmvc配置类,产生springmvc容器(本质还是spring容器)
    protected WebApplicationContext createServletApplicationContext() {
    
    
        //初始化WebApplicationContext对象
        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
        //加载指定配置类
        ctx.register(SpringMvcConfig.class);
        return ctx;
    }

    //设置由springmvc控制器处理的请求映射路径
    protected String[] getServletMappings() {
    
    
        return new String[]{
    
    "/"};
    }

    //加载spring配置类
    protected WebApplicationContext createRootApplicationContext() {
    
    
        return null;
    }
}

annotation

Annotation 1: @Controller

name @Controller
type class annotation
Location Above the SpringMVC controller class definition
effect Set the core controller bean of SpringMVC

Annotation 2: @RequestMapping

name @RequestMapping
type class annotation or method annotation
Location Above the SpringMVC controller class or method definition
effect Set the current controller method request access path
related attributes value (default), request access path

Annotation 3: @ResponseBody

name @ResponseBody
type class annotation or method annotation
Location Above the SpringMVC controller class or method definition
effect Set the response content of the current controller method as the current return value without parsing

SpringMVC entry program development summary (1+N)

  • one time job
    • Create a project, set up a server, and load a project
    • import coordinates
    • Create a web container startup class, load the SpringMVC configuration, and set the SpringMVC request interception path
    • SpringMVC core configuration class (set configuration class, scan controller package, load Controller controller bean)
  • work multiple times
    • Define the controller class that handles the request
    • Define the controller method for processing the request, and configure the mapping path (@RequestMapping) and return json data (@ResponseBody)

Spring MVC workflow

start server initialization

initialization

insert image description here

  • The server starts, executes the ServletContainersInitConfig class, and initializes the web container function similar to the previous web.xml
  • Execute the createServletApplicationContext method to create a WebApplicationContext object
    • This method loads the SpringMVC configuration class SpringMvcConfig to initialize the SpringMVC container
  • Load SpringMvcConfig configuration class

insert image description here

  • Execute @ComponentScan to load the corresponding bean
  • Scan the annotations on all classes under the specified package and its subpackages, such as the @Controller annotation on the Controller class
  • Load UserController, each @RequestMapping name corresponds to a specific method
    • /saveAt this point , the corresponding relationship with the save method is established

insert image description here

  • Execute the getServletMappings method to set the path rules for SpringMVC interception requests
    • /Represents the path rule of the intercepted request, which can only be handed over to SpringMVC to process the request after being intercepted

insert image description here

single request process

  1. send requesthttp://localhost/save
  2. The web container finds that the request meets the SpringMVC interception rules, and hands the request to SpringMVC for processing
  3. Parsing the request path /save
  4. The corresponding method save() is executed by /save matching
    • The fifth step above has established a corresponding relationship between the request path and the method, and the corresponding save method can be found through /save
  5. Execute save()
  6. It is detected that @ResponseBody directly returns the return value of the save() method as the response body to the requester

Guess you like

Origin blog.csdn.net/weixin_45696320/article/details/130240965