SpringMVC [SpringMVC (entry case, execution process, encapsulated as a simple data type, encapsulated as an object type, encapsulated as a collection type)] (1)-Comprehensive and detailed explanation (learning summary --- from entry to deepening)

 

 

Table of contents

Introduction to Spring MVC

SpringMVC entry case

SpringMVC execution process 

 Components of Spring MVC

Component Workflow 

SpringMVC parameter acquisition_encapsulation as a simple data type

SpringMVC parameter acquisition_encapsulation as object type 

Encapsulates a single object

SpringMVC parameter acquisition_encapsulation as a collection type 

Encapsulated as a List collection

Encapsulated as collection of simple data types


 

Introduction to Spring MVC

 MVC model

The full name of MVC is Model View Controller, which is a pattern for designing and creating web applications. These three words represent the three parts of the web application:

Model: Refers to the data model. Business logic for storing data and handling user requests. In Web applications, JavaBean objects, business models, etc. all belong to Model.

View (view): used to display the data in the model, usually jsp or html files.

Controller (controller): is the part of the application that handles user interaction. Accept the request made by the view, hand over the data to the model for processing, and hand over the processed result to the view for display.

 SpringMVC

SpringMVC is a lightweight Web framework based on the MVC pattern. It is a module of the Spring framework and can be directly integrated with Spring. SpringMVC replaces the Servlet technology. It uses a set of annotations to make a simple Java class a controller for processing requests without implementing any interfaces.

SpringMVC entry case

 Next, we write an entry case for SpringMVC

1. Use maven to create a web project and complete the package structure.

2. Introduce related dependencies and tomcat plug-ins

<dependencies>
    <!-- Spring核心模块 -->
    <dependency>
      <groupId>org.springframework</groupId>
        <artifactId>springcontext</artifactId>
        <version>5.2.12.RELEASE</version>
    </dependency>
    <!-- SpringWeb模块 -->
    <dependency>
      <groupId>org.springframework</groupId>
        <artifactId>springweb</artifactId>
        <version>5.2.12.RELEASE</version>
    </dependency>
    <!-- SpringMVC模块 -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>springwebmvc</artifactId>
        <version>5.2.12.RELEASE</version>
    </dependency>
    <!-- Servlet -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servletapi</artifactId>
        <version>2.5</version>
        <scope>provided</scope>
    </dependency>
    <!-- JSP -->
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
        <artifactId>jsp-api</artifactId>
        <version>2.0</version>
        <scope>provided</scope>
    </dependency>
 </dependencies>
<build>
    <plugins>
        <!-- tomcat插件 -->
        <plugin>
          <groupId>org.apache.tomcat.maven</groupId>
            <artifactId>tomcat7-maven-plugin</artifactId>
            <version>2.1</version>
            <configuration>
                <port>8080</port>
                <path>/</path>
                <uriEncoding>UTF8</uriEncoding>
                <server>tomcat7</server>
                <systemProperties>
                  <java.util.logging.SimpleFormatter.format>%1$tH:%1$tM:%1$tS %2$s%n%4$s: %5$s%6$s%n
                  </java.util.logging.SimpleFormatter.format>
                </systemProperties>
            </configuration>
        </plugin>
    </plugins>
</build>

3. Configure the front controller DispatcherServlet in web.xml.

<web-app>
    <display-name>Archetype Created Web Application</display-name>
    <!--SpringMVC前端控制器,本质是一个 Servlet,接收所有请求,在容器启动时就会加载-->
    <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:springmvc.xml</paramvalue>
        </init-param>
        <load-on-startup>1</load-onstartup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

4 Write the SpringMVC core configuration file springmvc.xml, which is written in the same way as the Spring configuration file.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:mvc="http://www.springframework.org/schema/mvc"
      xmlns:context="http://www.springframework.org/schema/context"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
      http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans.xsd
      http://www.springframework.org/schema/mvc
      http://www.springframework.org/schema/mvc/spring-mvc.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context.xsd">
    <!-- 扫描包 -->
    <context:component-scan base-package="com.tong"/>
    <!-- 开启SpringMVC注解的支持 -->
    <mvc:annotation-driven/>
</beans>

5. Write the controller

@Controller
public class MyController1 {
    // 该方法的访问路径是/c1/hello1
    @RequestMapping("/c1/hello1")
    public void helloMVC(){
        System.out.println("hello SpringMVC!");
   }
}

6 Use the tomcat plug-in to start the project, visit http://localhost:8080/c1/hello1

SpringMVC execution process 

 Components of Spring MVC

DispatcherServlet: Front controller, accepts all requests and calls other components.

HandlerMapping: The processor mapper, which finds the execution chain of the method according to the configuration.

HandlerAdapter: Handler adapter, find the corresponding handler according to the method type.

ViewResolver: view resolver, find the specified view.

Component Workflow 

1. The client sends the request to the front controller.

2. The front-end controller sends the request to the processor mapper, and the processor mapper finds the execution chain of the method according to the path and returns it to the front-end controller.

3. The front controller sends the execution chain of the method to the processor adapter, and the processor adapter finds the corresponding processor according to the method type.

4. The processor executes the method and returns the result to the front controller.

5. The front controller sends the result to the view resolver, and the view resolver finds the location of the view file.

6. The view renders the data and displays the result to the client.

SpringMVC parameter acquisition_encapsulation as a simple data type

 

 In Servlet, we get request parameters through request.getParameter(name) . There are two problems with this approach:

 1. When there are many request parameters, there will be code redundancy.

 2. Tightly coupled with the container.

SpringMVC supports parameter injection to obtain request data, that is, request parameters are directly encapsulated into method parameters. The usage is as follows:

 1. Write the controller method

// 获取简单类型参数
@RequestMapping("/c1/param1")
public void simpleParam(String username,int age){
    System.out.println(username);
    System.out.println(age);
}

2. When accessing the method, the request parameter name is the same as the method parameter name, and the automatic encapsulation can be completed.

SpringMVC parameter acquisition_encapsulation as object type 

 SpringMVC supports directly encapsulating parameters into objects, written as follows:

Encapsulates a single object

1. Write entity classes

public class Student {
    private int id;
    private String name;
    private String sex;
    // 省略getter/setter/tostring
}

2. Write the controller method

// 获取对象类型参数
@RequestMapping("/c1/param2")
public void objParam(Student student){
    System.out.println(student);
}

3. When accessing the method, the request parameter name is the same as the attribute name of the method parameter, and then the automatic encapsulation can be completed.

Encapsulate associated objects 

1. Write entity classes

public class Address {
    private String info; //地址信息
    private String postcode; //邮编
    // 省略getter/setter/tostring
}
public class Student {
    private int id;
    private String name;
    private String sex;
    private Address address; // 地址对象
    // 省略getter/setter/tostring
}

2. Write the controller method

// 获取关联对象类型参数
@RequestMapping("/c1/param3")
public void objParam2(Student student){  
    System.out.println(student);
}

3. When accessing the method, the request parameter name is the same as the attribute name of the method parameter, and then the automatic encapsulation can be completed.

We can also send requests with parameters using a form:

<%@ page
contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
     <title>表单提交</title>
</head>
<body>
     <form action="/c1/param3" method="post">
         id:<input name="id">
         姓名:<input name="name">
         性别:<input name="sex">
         住址:<input name="address.info">
         邮编:<input name="address.postcode">
         <input type="submit">
     </form>
 </body>
</html>

SpringMVC parameter acquisition_encapsulation as a collection type 

 SpringMVC supports encapsulation of parameters as List or Map collections, written as follows:

Encapsulated as a List collection

Encapsulated as collection of simple data types

1. Write the controller method

// 绑定简单数据类型List参数,参数前必须添加
@RequestParam注解
@RequestMapping("/c1/param4")
public void listParam(@RequestParamList<String> users){
    System.out.println(users);
}

This method can also bind array types:

@RequestMapping("/c1/param5")
public void listParam2(@RequestParam String[] users){
    System.out.println(users[0]);
    System.out.println(users[1]);
}

2. Request parameter writing method

Encapsulated as a collection of object types 

SpringMVC does not support encapsulating parameters into a List collection of object type, but it can be encapsulated into an object with a List property.

1. Write entity classes

public class Student {
    private int id;
    private String name;
    private String sex;
    private List<Address> address; // 地址集合
    // 省略getter/setter/tostring
}

2. Write the controller method

// 对象中包含集合属性
@RequestMapping("/c1/param6")
public void listParam3(Student student){
    System.out.println(student);
}

3. Request parameter writing method

Encapsulated as a Map collection 

Similarly, if SpringMVC wants to encapsulate the Map collection, it needs to be encapsulated into an object with a Map property.

1. Write entity classes

public class Student {
    private int id;
    private String name;
    private String sex;
    private Map<String,Address> address;
    // 地址集合
    // 省略getter/setter/tostring
}

2. Write the controller method

// 对象中包含Map属性
@RequestMapping("/c1/param7")
public void mapParam(Student student){  
    System.out.println(student);
}

3. Request parameter writing method

Guess you like

Origin blog.csdn.net/m0_58719994/article/details/131744917