软件开发实训(720)2.0

内容关键词:表单绑定、数据

授课老师:720张森鹏

知识笔记:数据绑定是将用户输入绑定到领域模型的一种特性。有了数据绑定,类型总是为String的HTTP请求参数,可用于填充不同类型的对象属性。
1.数据绑定概览
基于HTTP的特性,所有HTTP请求参数的类型均为字符串。
有了数据绑定,就不再需要ProductForm类,也不需要解析Product对象的price属性。
@RequestMapping(value='product_save')
public String saveProduct(Product product, Model model)

数据绑定的另一个好处是:当输入验证失败时,它会重新生成一个HTML表单。手工编写HTML代码时,必须记着用户之前输入的值,重新填充输入字段。有了Spring的数据绑定和表单标签库后,它们就会替你完成这些工作

2.重要笔记:

1.数组
//数组绑定/arrayType?name=tom&name=lucy
@RequestMapping('/arrayType')
@ResponseBody
public String array(String[] name){
StringBuilder sb=new StringBuilder();
for (String item :name){
sb.append(item).append(' ');
}
return sb.toString();
}
2. 对象
//todo 对象绑定/objectType?name=tom&age=10
//todo 复合对象
///objectType?name=tom&age=10&contactinfo.phone=10086&contactinfo.address=china
//todo 属性的多个对象/objectType?user.name=tom&age=10
@RequestMapping('/objectType')
@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.');
}
3. 集合类型
List
//todo 集合数据绑定
//todo 数据收集对象UserListForm,绑定的是里面的users对象
//todo/list?users[0].name=tom&users[1].name=lucy
// 请求索引要连续,不然会浪费很多空间(空对象)
@RequestMapping(value '/list')
@ResponseBody
public String list(UserListForm userList){
return userList.toString();
}
Set
//todoset的绑定与list的不同,set要初始化size大小,源码里面会判断index与size关系
// set 主要判断重复,在初始化set对象大小之后,重写hashcode和equals方法,空对象1个,size为1
// /set?users[0].name=tom&users[1].name=lucy
@RequestMapping(value '/set')
@ResponseBody
public String set(UserSetForm userSet){
return userSet.toString();
}
Map
//todo/map?users[x].name=tom&users[y].name=lucy
@RequestMapping(value '/map')
@ResponseBody
public String map(UserMapForm userMap){
return userMap.toString();
}
4. Json数据
在maven配置文件中加入jackson-databind的jar包依赖支持对json的解析
//todo json绑定 Content-Type:application/json
// {
// 'name':'tom',
// 'age':10,
// 'contactInfo':{
// 'address':'shenzhen',
// 'phone':10086
// }
//}
@RequestMapping(value '/json')
@ResponseBody
public String json(@RequestBody User user){
return user.toString();
}

猜你喜欢

转载自blog.csdn.net/qq_41546168/article/details/80017003