1.基本类型、包装类型、数组类型处理
//整型类型绑定
@RequestMapping(value = "baseType.do")
@ResponseBody
public String baseType(int age){
return "age:"+ age;
}
//包装类型绑定
@RequestMapping(value = "baseType2.do")
@ResponseBody
public String baseType2(Integer age){
return "age:"+ age;
}
//数组类型绑定
@RequestMapping(value = "array.do")
@ResponseBody
public String array(String[] name){
StringBuilder sbf = new StringBuilder();
for (String item:name) {
sbf.append(item).append(" ");
}
return sbf.toString();
}
2.简单对象、复杂对象的处理
//对象类型绑定
http://localhost:8080/object.do?name=Tom&age=10
http://localhost:8080/object.do?name=Tom&age=10&contactInfo.phone=10086
http://localhost:8080/object.do?user.name=Tom&admin.name=Lucy
@RequestMapping(value = "object.do")
@ResponseBody
public String object(User user, Admin admin) {
return user.toString()+" "+ admin.toString();
}
//复杂对象类型绑定
//如果遇到多个对象,则采用该种方法进行区分,如果没有这两个方法区分,则会产生
//User{name='null', age=null, contactInfo=null} Admin{name='null', age=null}的结果
@InitBinder("user")
public void initUser(WebDataBinder binder){
binder.setFieldDefaultPrefix("user.");
}
@InitBinder("admin")
public void initAdmin(WebDataBinder binder){
binder.setFieldDefaultPrefix("admin.");
}
3.List、Set、Map处理
//list类型绑定
@RequestMapping(value = "list.do")
@ResponseBody
public String list(UserListForm userListForm) {
return userListForm.toString();
}
http://localhost:8080/list.do?users[0].name=Tom&users[1].name=Lucy
UserListForm{users=[User{name='Tom', age=null, contactInfo=null}, User{name='Lucy', age=null, contactInfo=null}]}
如果是http://localhost:8080/list.do?users[0].name=Tom&users[20].name=Lucy,则会造成中间19个对象是null,变成坑,所以请求索引一定要是连续的!
//set类型绑定
set和list不同,set需要初始化,set在实际应用中一般用于对象的重复判断和排除重复
例如student对象,有name和email两个属性,如果这两个属性相等则判断为一个对象,需要重写hashcode和equals方法和重复判断的逻辑,SpringMVC对Set不够友好,在判断对象时需要进行很多操作,所以一般选择优先选List作为绑定
@RequestMapping(value = "set.do")
@ResponseBody
public String set(UserSetForm userSetForm) {
return userSetForm.toString();
}
//map类型绑定
@RequestMapping(value = "map.do")
@ResponseBody
public String map(UserMapForm userMapForm) {
return userMapForm.toString();
}
http://localhost:8080/map.do?users[%27X%27].name=Tom&users[%27X%27].age=10&users[%27Y%27].name=Lucy
UserMapForm{users={X=User{name='Tom', age=10, contactInfo=null}, Y=User{name='Lucy', age=null, contactInfo=null}}}
4.Json、Xml处理
//Json处理
@RequestMapping(value = "json.do")
@ResponseBody
public String json(@RequestBody User user) {
return user.toString();
}
{
"name":"tom",
"age":"11",
"contactInfo":{
"address":"bj",
"phone":"10086"
}
}
//XML处理
@RequestMapping(value = "xml.do")
@ResponseBody
public String xml(@RequestBody Admin admin) {
return admin.toString();
}
<?xml version="1.0" encoding="UTF-8" ?>
<admin>
<name>Jim</name>
<age>16</age>
</admin>