程序的主要几个比较重要且复杂用法之六SpringMVC数据绑定
程序的主要几个比较重要且复杂用法之六SpringMVC数据绑定
1.绑定基本类型(如int, double等),就要求不能传入空或类型出错
如要传入空则需要用@RequestParam进行默认值如下
//http://localhost:8099/exam_3/BasicType?xage=11
//http://localhost:8099/exam_3/BasicType 默认为10
@RequestMapping("/BasicType")
@ResponseBody
public String BasicType(@RequestParam(value="xage", required=false, defaultValue="10") int age)
{
return "age=" + age;
}
2.绑定数组
// http://localhost:8099/exam_3/ArrayType?ages=1&ages=2
@RequestMapping("/ArrayType")
@ResponseBody
public String ArrayType(String[] ages) {
StringBuilder sb = new StringBuilder();
for (String s : ages) {
sb.append(s + " ");
}
return sb.toString();
}
3.绑定对象
//http://localhost:8099/exam_3/ObjectBind1?userName=tom&address=china
@RequestMapping("/ObjectBind1")
@ResponseBody
public String ObjectBind1(User user) {
return user.toString();
}
有子对象的绑定
http://localhost:8099/exam_3/ObjectBind3?user.userName=tom&user.address=china&info.tel=13555&info.email=adsfasf
有同属性对象
http://localhost:8099/exam_3/ObjectBind3?user.userName=tom&user.address=china&admin.userName=13555&admin.address=adsfasf
@RequestMapping("/ObjectBind2")
@ResponseBody
public String ObjectBind2(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.");
}
浙公网安备 33010602011771号