SpringMVC数据绑定一(基本类型、数组和对象(简单对象、层级对象、多参数对象))
一、int和Integer类型
如:参数为int类型的请求
@Controller public class TestController { @RequestMapping(value="/baseType") @ResponseBody//直接返回字符串界面,不用请求获取jsp页面。去掉报404错误,找不到页面。 public String baseType(int age) { return "age:"+age; } }
1。参数为int类型的请求,若没有传入参数,报500的错误
2.参数为int类型的请求,若参数类型错误,报400的错误
正确
1.2@RequestParam
@Controller public class TestController { @RequestMapping(value="/baseType") @ResponseBody //@RequestParam注解value属性为传参别名,defaultValue默认赋值,required是否必须传值默认true。 //若把required设置为false,不传参则不报错 public String baseType(@RequestParam(value="xage",defaultValue="1",required=false) int age) { return "age:"+age; } }
如:参数为Integer类型
1.若参数请求为Integer类型,没有参数,自动给参数赋值为null
2.若参数请求为Integer类型,参数l类型不匹配,同上也报400错误。
二、参数为数组类型
//http://127.0.0.1:8080/SpringMVC/array?name=Tom&name=Lucy&name=jim @RequestMapping(value="array") @ResponseBody public String array(String[] name) { StringBuilder sbf = new StringBuilder(); for(String item:name) { sbf.append(item).append(" "); } return sbf.toString(); }
三、参数为对象(简单对象)
//model public class User { private String name; private Integer age; //getter and setting ...... @Override public String toString() { return "User [name=" + name + ", age=" + age + "]"; } }
//http://127.0.0.1:8080/SpringMVC/object?name=Tom&age=20 @RequestMapping(value="object") @ResponseBody public String object(User user) { return user.toString(); }
三、参数为对象(多层级对象)
1.1model
//联系信息类 public class ContactInfo { private String phone; private String address; //getting and setting............ @Override public String toString() { return "ContactInfo [phone=" + phone + ", address=" + address + "]"; } }
//用户类 public class User { private String name; private Integer age; private ContactInfo contactInfo; //getting and setting............ @Override public String toString() { return "User [name=" + name + ", age=" + age + ", contactInfo=" + contactInfo + "]"; } }
//http://127.0.0.1:8080/SpringMVC/object?name=Tom&age=20&contactInfo.phone=10086&contactInfo.address=ss @RequestMapping(value="object") @ResponseBody public String object(User user) { return user.toString(); }
结果显示:
1.2 若参数为2个对象
@RequestMapping(value="object") @ResponseBody public String object(User user,Admin admin) { return user.toString()+" "+admin.toString(); }
两个参数对象被赋予相同的参数
解决办法@InitBinder
//http://127.0.0.1:8080/SpringMVC/object?user.name=Tom&age=20&admin.name=lucy
@RequestMapping(value="object") @ResponseBody public String object(User user,Admin admin) { return user.toString()+" "+admin.toString(); } @InitBinder("user") public void initUser(WebDataBinder binder) { binder.setFieldDefaultPrefix("user."); } @InitBinder("admin") public void initAdmin(WebDataBinder binder) { binder.setFieldDefaultPrefix("admin."); }