1. 基本类型的数据封装
//http://localhost:8080/spring_mvc_01/user/save8?name=bitqian&age=19
@RequestMapping(value = "/save8")
@ResponseBody
public void save8(String name, int age) {
System.out.println(name + "\t" + age);
}
2. pojo(bean)类型的封装
//http://localhost:8080/spring_mvc_01/user/save8?name=bitqian&age=19
@RequestMapping(value = "/save9")
@ResponseBody
public void save9(User user) {
System.out.println(user);
}
3. 数组类型
@RequestMapping(value = "/save10")
@ResponseBody
public void save10(String[] arr) {
// http://localhost:8080/spring_mvc_01/user/save10?arr=abc&arr=def&arr=ghi
System.out.println(Arrays.asList(arr));
}
4. list集合类型
1.通过viewobject视图对象类,里面装集合
- view object 实体
package com.bitqian.entity;
import java.util.List;
/**
* user view object
* @author echo lovely
* @date 2020/9/1 20:25
*/
public class ViewObject {
private List<User> userList;
public List<User> getUserList() {
return userList;
}
public void setUserList(List<User> userList) {
this.userList = userList;
}
@Override
public String toString() {
return "ViewObject{" +
"userList=" + userList +
'}';
}
}
- 接收表单提交的数据
// 封装集合1
@RequestMapping(value = "/save11")
@ResponseBody
public void save11(ViewObject vo) {
System.out.println(vo);
}
- 表单提交
<%--
Created by IntelliJ IDEA.
User: echo lovely
Date: 2020/9/1
Time: 20:31
使用spring-mvc框架封装集合
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>spring -mvc框架封装集合</title>
</head>
<body>
<form action="user/save11" method="post">
<input type="text" name="userList[0].name"/> <br/>
<input type="text" name="userList[0].age"> <br/>
<input type="text" name="userList[1].name"/> <br/>
<input type="text" name="userList[1].age"> <br/>
<input type="submit" value="提交" />
</form>
</body>
</html>
- 通过ajax提交json集合数据,mvc自动封装(静态资源404问题)
- 页面
<%--
Created by IntelliJ IDEA.
User: echo lovely
Date: 2020/9/1
Time: 20:58
ajax 提交json格式的数据
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>ajax 提交json格式的数据</title>
<%--静态资源权限问题..--%>
<script src="js/jquery.min.js"></script>
<script>
$(function () {
let userList = new Array();
userList.push({
name:"jack", age:19});
userList.push({
name:"rose", age:18});
$.ajax({
url: "user/save12",
type: "post",
data: JSON.stringify(userList),
contentType: "application/json;charset=utf-8",
success: function (data) {
console.log('data', data);
},
error: function (e) {
console.log(e);
}
});
});
</script>
</head>
<body>
</body>
</html>
- @requestBody封装数据到集合
@RequestMapping(value = "/save12")
@ResponseBody
public void save12(@RequestBody List<User> list) {
System.out.println(list);
}
- 加载静态资源
<!--加载静态资源-->
<mvc:resources mapping="/js/**" location="/js/"/>
<!--<mvc:default-servlet-handler/>-->