json数据绑定
/**
* json数据绑定
* @param people
* @return
* {
"sex":"man",
"address":"guangzhou",
"user":{
"name":"zhangsan",
"age":"500"
}
}
*/
@RequestMapping("byJson.do")
@ResponseBody
public String byJson(@RequestBody People people){
return people.toString();
}
public class People {
private String sex;
private String address;
private User user;
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
@Override
public String toString() {
return "People{" +
"sex='" + sex + '\'' +
", address='" + address + '\'' +
", user=" + user +
'}';
}
}
json数据绑定要在参数中加上@RequestBody注解,@RequestBody就是把传过来的json数据反序列化绑定到控制器上。
xml数据绑定
/**
* xml数据绑定
* @param admin
* @return
* <?xml version="1.0" encoding="UTF-8" ?>
<admins>
<name>Jim</name>
<age>16</age>
</admins>
*/
@RequestMapping("byXml.do")
@ResponseBody
public String byXml(@RequestBody Admin admin){
return admin.toString();
}
@XmlRootElement(name="admins")
public class Admin {
private String name;
private Integer age;
@XmlElement(name="name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@XmlElement(name="age")
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Admin{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
1、xml数据绑定必须要在实体类里面加上@XmlRootElement注解,在属性上加上@XmlElement@XmlElement(name=”age”):此时就会将xml 里面对应的age数据添加到实体类中的age属性中去。
2、xml数据绑定需要“spring-oxm”这个jar包提供支持
springMVC数据绑定【一】——基本类型、包装类型、数组绑定
springMVC数据绑定【二】——简单对象、多层级对象和同对象数据绑定
springMVC数据绑定【三】——List、Set和Map绑定