美文网首页
122、【JavaEE】【SpringMVC】SpringMVC

122、【JavaEE】【SpringMVC】SpringMVC

作者: yscyber | 来源:发表于2021-10-29 22:25 被阅读0次

1、GET / POST&Content-Type: application/x-www-form-urlencoded

  • 包括“超链接”(GET)、“普通表单提交”(GET/POST)、“Ajax 等提交”(GET/POST)

1.1、逐个接收

  • 方法中参数名与前端name一致,直接使用。
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Spring MVC</title>
</head>
<body>
<form method="post" enctype="application/x-www-form-urlencoded" action="http://localhost:8080/web4/data">
    <input type="text" name="id" autocomplete="off"/>
    <br/>
    <input type="text" name="name" autocomplete="off"/>
    <br/>
    <input type="submit" value="提交"/>
</form>
</body>
</html>
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;

@Controller
public class MyRequestController {

    @PostMapping(path = "/data")
    public void myData(Integer id, String name) {
        System.out.println(id);
        System.out.println(name);
    }

}
  • 方法中参数名与前端name不一致,使用@RequestParam注解。
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Spring MVC</title>
</head>
<body>
<form method="post" enctype="application/x-www-form-urlencoded" action="http://localhost:8080/web4/data">
    <input type="text" name="mid" autocomplete="off"/>
    <br/>
    <input type="text" name="mName" autocomplete="off"/>
    <br/>
    <input type="submit" value="提交"/>
</form>
</body>
</html>
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class MyRequestController {

    @PostMapping(path = "/data")
    public void myData(@RequestParam("mid") Integer id, @RequestParam("mName") String name) {
        System.out.println(id);
        System.out.println(name);
    }

}

1.2、数组接收

  • 方法中使用数组接收的情况主要是前端有重复的name,亦可以使用@RequestParam注解。
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Spring MVC</title>
</head>
<body>
<form method="post" enctype="application/x-www-form-urlencoded" action="http://localhost:8080/web4/data">
    <input type="checkbox" name="hobbies" value="basketball"/>篮球
    <br/>
    <br/>
    <input type="checkbox" name="hobbies" value="soccer"/>足球
    <br/>
    <br/>
    <input type="checkbox" name="hobbies" value="volleyball"/>排球
    <br/>
    <br/>
    <input type="submit" value="提交"/>
</form>
</body>
</html>
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;

@Controller
public class MyRequestController {

    @PostMapping(path = "/data")
    public void myData(String[] hobbies) {
        if (hobbies != null) {
            for (String hobby : hobbies) {
                System.out.println(hobby);
            }
        } else {
            System.out.println("null");
        }

    }

}

1.3、封装成对象接收

  • 对象中的成员变量名与前端name保持一致时,直接封装成方法中提供的对象。
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Spring MVC</title>
</head>
<body>
<form method="post" enctype="application/x-www-form-urlencoded" action="http://localhost:8080/web4/data">
    <input type="text" name="id" autocomplete="off"/>
    <br/>
    <br/>
    <input type="text" name="name" autocomplete="off"/>
    <br/>
    <br/>
    <input type="submit" value="提交"/>
</form>
</body>
</html>
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

@NoArgsConstructor
@AllArgsConstructor
@Data
@ToString
public class User {

    private Integer id;

    private String name;

}
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;

@Controller
public class MyRequestController {

    @PostMapping(path = "/data")
    public void myData(User user) {
        System.out.println(user); // 直接封装至方法中所提供的对象(User user)中
    }

}

1.4、封装成对象 — 含复杂数据类型

  • “含复杂数据类型”即包含对象、List、Map 等。

  • 对象中的成员变量名与前端name保持一致,直接封装成方法中提供的对象。

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Spring MVC</title>
</head>
<body>
<form method="post" enctype="application/x-www-form-urlencoded" action="http://localhost:8080/web4/data">
    <p>普通数据类型</p>
    <input type="text" name="str" autocomplete="off"/>
    <br/>
    <br/>
    <p>引用数据类型</p>
    <input type="text" name="user.id" autocomplete="off"/>
    <br/>
    <br/>
    <input type="text" name="user.name" autocomplete="off"/>
    <br/>
    <br/>
    <p>List</p>
    <p>第一个元素</p>
    <input type="text" name="userList[0].id" autocomplete="off"/>
    <br/>
    <br/>
    <input type="text" name="userList[0].name" autocomplete="off"/>
    <br/>
    <br/>
    <p>第二个元素</p>
    <input type="text" name="userList[1].id" autocomplete="off"/>
    <br/>
    <br/>
    <input type="text" name="userList[1].name" autocomplete="off"/>
    <br/>
    <br/>
    <p>Map</p>
    <p>第一个元素</p>
    <input type="text" name="userMap['u1'].id" autocomplete="off"/>
    <br/>
    <br/>
    <input type="text" name="userMap['u1'].name" autocomplete="off"/>
    <br/>
    <br/>
    <p>第二个元素</p>
    <input type="text" name="userMap['u2'].id" autocomplete="off"/>
    <br/>
    <br/>
    <input type="text" name="userMap['u2'].name" autocomplete="off"/>
    <br/>
    <br/>
    <input type="submit" value="提交"/>
</form>
</body>
</html>
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

@NoArgsConstructor
@AllArgsConstructor
@Data
@ToString
public class User {

    private Integer id;

    private String name;

}
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

import java.util.List;
import java.util.Map;

@NoArgsConstructor
@AllArgsConstructor
@Data
@ToString
public class User2 {

    private String str;

    private User user;

    private List<User> userList;

    private Map<String, User> userMap;

}
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;

@Controller
public class MyRequestController {

    @PostMapping(path = "/data")
    public void myData(User2 user2) {
        System.out.println(user2);
    }

}

2、POST&Content-Type: multipart/form-data

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.8</version>
        </dependency>

        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.4</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.3.3</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.20</version>
            <scope>provided</scope>
        </dependency>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <context:component-scan base-package="com.yscyber.mvc"/>

    <mvc:annotation-driven/>

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

    <!-- CommonsMultipartResolver 处理 Content-Type 为 multipart/form-data 的 HTTP 请求报文  -->
    <!-- 注意:<bean> 的 id 必须是 multipartResolver,否则会报错 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 所有上传的文件总大小不超过5MB -->
        <property name="maxUploadSize" value="5242880"/>
        <property name="defaultEncoding" value="UTF-8"/>
    </bean>

</beans>

2.1、含单个文件

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Spring MVC</title>
</head>
<body>
<form action="http://localhost:8080/web4/data" method="post" enctype="multipart/form-data">
    <input type="text" name="str" autocomplete="off"/>
    <br/>
    <br/>
    <input type="file" name="f"/>
    <br/>
    <br/>
    <input type="submit" value="提交"/>
</form>
</body>
</html>
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class MyRequestController {

    @RequestMapping(method = RequestMethod.POST, path = "/data")
    public void myData(String str, MultipartFile f) {
        System.out.println(str);
        System.out.println(f.getOriginalFilename());
    }

}
  • 当前端的name与方法中的参数名不一致的时候,可以使用@RequestParam注解。
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Spring MVC</title>
</head>
<body>
<form action="http://localhost:8080/web4/data" method="post" enctype="multipart/form-data">
    <input type="text" name="str" autocomplete="off"/>
    <br/>
    <br/>
    <input type="file" name="f"/>
    <br/>
    <br/>
    <input type="submit" value="提交"/>
</form>
</body>
</html>
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class MyRequestController {

    @PostMapping("/data")
    public void myData(@RequestParam("str") String string, @RequestParam("f") MultipartFile file) {
        System.out.println(string);
        System.out.println(file.getOriginalFilename());
    }

}

2.2、含多个文件

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Spring MVC</title>
</head>
<body>
<form action="http://localhost:8080/web4/data" method="post" enctype="multipart/form-data">
    <input type="text" name="str" autocomplete="off"/>
    <br/>
    <br/>
    <input type="file" name="f" multiple/>
    <br/>
    <br/>
    <input type="submit" value="提交"/>
</form>
</body>
</html>
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class MyRequestController {

    @PostMapping("/data")
    public void myData(@RequestParam("str") String string, @RequestParam("f") MultipartFile[] files) {
        System.out.println(string);
        for (MultipartFile file : files) {
            System.out.println(file.getOriginalFilename());
        }
    }

}
  • 前端出现多个<input type="file"/>。要么前端是name相同,方法中使用数组参数接收;要么前端是name不同,方法中使用不同参数接收。
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Spring MVC</title>
</head>
<body>
<form action="http://localhost:8080/web4/data" method="post" enctype="multipart/form-data">
    <input type="text" name="str" autocomplete="off"/>
    <br/>
    <br/>
    <input type="file" name="f"/>
    <br/>
    <br/>
    <input type="file" name="f">
    <br/>
    <br/>
    <input type="submit" value="提交"/>
</form>
</body>
</html>
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class MyRequestController {

    @PostMapping("/data")
    public void myData(@RequestParam("str") String string, @RequestParam("f") MultipartFile[] files) {
        System.out.println(string);
        for (MultipartFile file : files) {
            System.out.println(file.getOriginalFilename());
        }
    }

}

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Spring MVC</title>
</head>
<body>
<form action="http://localhost:8080/web4/data" method="post" enctype="multipart/form-data">
    <input type="text" name="str" autocomplete="off"/>
    <br/>
    <br/>
    <input type="file" name="f1"/>
    <br/>
    <br/>
    <input type="file" name="f2">
    <br/>
    <br/>
    <input type="submit" value="提交"/>
</form>
</body>
</html>
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class MyRequestController {

    @PostMapping("/data")
    public void myData(@RequestParam("str") String string, @RequestParam("f1") MultipartFile file1, @RequestParam("f2") MultipartFile file2) {
        System.out.println(string);
        System.out.println(file1.getOriginalFilename());
        System.out.println(file2.getOriginalFilename());
    }

}

2.3、仍可以使用封装对象接收

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Spring MVC</title>
</head>
<body>
<form action="http://localhost:8080/web4/data" method="post" enctype="multipart/form-data">
    <input type="text" name="str" autocomplete="off"/>
    <br/>
    <br/>
    <input type="file" name="f1"/>
    <br/>
    <br/>
    <input type="file" name="f2">
    <br/>
    <br/>
    <input type="submit" value="提交"/>
</form>
</body>
</html>
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

import org.springframework.web.multipart.MultipartFile;

@NoArgsConstructor
@AllArgsConstructor
@Data
@ToString
public class User3 {

    private String str;

    private MultipartFile f1;

    private MultipartFile f2;

}
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@Controller
public class MyRequestController {

    @PostMapping("/data")
    public void myData(User3 obj) {
        System.out.println(obj.getStr());
        System.out.println(obj.getF1().getOriginalFilename());
        System.out.println(obj.getF2().getOriginalFilename());
    }

}

3、POST&Content-Type: application/json;charset=UTF-8

  • 使用 JSON 数据格式向后端传输数据

3.1、接收 JSON 字符串

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>MVC</title>
</head>
<body>
<form>
    <input type="text" id="str1" autocomplete="off"/>
    <input type="text" id="str2" autocomplete="off"/>
    <input type="button" id="btn" value="提交"/>
</form>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
<script>
    $("#btn").on("click", function() {
        let myObj = {
            str1: $("#str1").val(),
            str2: $("#str2").val()
        };

        $.ajax({
            contentType: "application/json;charset=utf-8",
            type: "POST",
            url: "http://localhost:8080/web4/data",
            data: JSON.stringify(myObj),
            success: function(result, status, xhr) {
                console.log(status)
            },
            error: function(xhr, status, error) {
                console.log(status)
            }
        });
    });
</script>
</body>
</html>
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@Controller
public class MyRequestController {

    @PostMapping("/data")
    public void myData(@RequestBody String json) {
        System.out.println(json);
    }

}

3.2、接收时 JSON 字符串直接转对象

  • 要求对象中的成员变量名与 JSON 中的属性名一致,才能实现自动转换。

  • 如果要实现接收的时候 JSON 自动转对象:

1、需要引入一个依赖,Jackson 是 Spring 官方推荐的 “JSON-对象”转换工具,如果没有特殊的需求,引入该依赖后,无需进行配置(其他的“JSON-对象”转换工具比如 Fastjson 等需要进行配置):

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.12.3</version>
</dependency>

2、在 Spring MVC 的配置文件中配置<mvc:annotation-driven/>

  • Spring MVC默认用org.springframework.http.converter.json.MappingJackson2HttpMessageConverter对 JSON 数据进行转换,所以需要引入 Jackson 的依赖。
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>MVC</title>
</head>
<body>
<form>
    <input type="text" id="str1" autocomplete="off"/>
    <input type="text" id="str2" autocomplete="off"/>
    <input type="button" id="btn" value="提交"/>
</form>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
<script>
    $("#btn").on("click", function() {
        let myObj = {
            str1: $("#str1").val(),
            str2: $("#str2").val()
        };

        $.ajax({
            contentType: "application/json;charset=utf-8",
            type: "POST",
            url: "http://localhost:8080/web4/data",
            data: JSON.stringify(myObj),
            success: function(result, status, xhr) {
                console.log(status)
            },
            error: function(xhr, status, error) {
                console.log(status)
            }
        });
    });
</script>
</body>
</html>
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

@NoArgsConstructor
@AllArgsConstructor
@Data
@ToString
public class User4 {

    private String str1;

    private String str2;

}
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@Controller
public class MyRequestController {

    @PostMapping("/data")
    public void myData(@RequestBody User4 user4) {
        System.out.println(user4);
    }

}

相关文章

网友评论

      本文标题:122、【JavaEE】【SpringMVC】SpringMVC

      本文链接:https://www.haomeiwen.com/subject/nypmaltx.html