转载:http://blog.csdn.net/u012792137/article/details/78330105
用户对象定义
@Entity
@Data
public class UserTestForm {
@Id
@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid",strategy = "com.example.springdbtest.util.Base58UuidGenerator")
public String id ;
//用户名
public String userName;
//年龄
public String age;
//教育经历
@OneToMany(cascade = CascadeType.ALL,fetch = FetchType.LAZY)
public List education;
}
教育经历对象定义
@Entity
@Data
public class Education {
@Id
@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid",strategy = "com.example.springdbtest.util.Base58UuidGenerator")
public String id ;
//入学时间
public String admissionDate;
//毕业院校
public String graduateFrom;
//毕业时间
public String graduateDate;
}
前端页面代码
后端数据代码
@PostMapping("/addUser")
@ResponseBody
public UserTestForm addUserForm(UserTestForm user){
log.info(user);
return user;
}
*注: 这里不可以用@RequestBody 注解
后端拿到的数据转为json格式
{
"id": null,
"userName": "lisa",
"age": "12",
"education": [
{
"id": null,
"admissionDate": "2013-09-01",
"graduateFrom": "北京大学",
"graduateDate": "2017-06-01"
},
{
"id": null,
"admissionDate": "2010-09-01",
"graduateFrom": "清华大学",
"graduateDate": "2013-06-01"
}
]
}
前端页面代码
后端代码
@PostMapping("/addUser")
@ResponseBody
public UserTestForm addUserForm(@RequestBody UserTestForm user){
log.info(user);
return user;
}
*说明 :
- 由于是Ajax提交 form表单中的命名不需要 education[1].graduateFrom
形式,甚至表单中所有name的名字都可不与后端对象对应,只要在Ajax中定义时与后端对应即可,但为了识别/操作/可读方面考虑不推荐
- 当后端不使用@RequestBody
注解时,前端ajax请求中data:user
,此时不需要指定contentType.
此时前端传到后端的是一个user对象
{
userName: "lisa",
age: "12",
education[0].admissionDate: "2013-09-01",
education[0].graduateFrom: "北京大学",
education[0].graduateDate: "2017-06-01",
education[1].admissionDate: "2010-09-01",
education[1].graduateDate: "2013-06-01",
education[1].graduateFrom: "清华大学"
}
@RequestBody
注解时,前端ajax请求中的 data:user2
,此时需指定 contentType:"applicaiton/json"
此时前端传后端的是一个json字符串
{
"userName": "lisa",
"age": "12",
"education": [
{
"admissionDate": "2013-09-01",
"graduateFrom": "北京大学",
"graduateDate": "2017-06-01"
},
{
"admissionDate": "2010-09-01",
"graduateFrom": "清华大学",
"graduateDate": "2013-06-01"
}
]
}
两种方式传到后端,后端接到的数据与form表单的效果一致。