4.集合对象绑定
1.List
Spring MVC并不支持直接将集合对象作为参数进行绑定,需要把集合对象作为属性才能绑定。
public class StudentList {
private List<StudentModel> studentList;
public List<StudentModel> getStudentList() {
return studentList;
}
public void setStudentList(List<StudentModel> studentList) {
this.studentList = studentList;
}
public String toString(){
return "StudentList["+"studentList="+studentList+"]";
}
}
@Controller
@RequestMapping("/example4/collectionController")
public class CollectionController {
@RequestMapping("/bindList.htm")
public String bindList(Model model,StudentList studentList){
model.addAttribute("msg", studentList.toString());
return "/example4/result";
}
}
StudentList为包装集合类,其中List集合作为属性实现数据绑定。
从结果看到,List集合创建了3个对象,虽然我们只对索引值为0和2的对象进行了赋值,但索引值为1的对象也被创建了。
2.Set
@Controller
@RequestMapping("/example5/collectionController")
public class CollectionController {
@RequestMapping("/bindSet.htm")
public String bindList(Model model,StudentSet studentSet){
model.addAttribute("msg", studentSet.toString());
return "/example5/result";
}
}
public class StudentSet {
//StudentModel的Set集合
private Set<StudentModel> studentSet;
public StudentSet(){
//Set集合必须被初始化,保证集合对象个数
studentSet=new HashSet();
studentSet.add(new StudentModel());
studentSet.add(new StudentModel());
studentSet.add(new StudentModel());
}
public Set<StudentModel> getStudentSet() {
return studentSet;
}
public void setStudentSet(Set<StudentModel> studentSet) {
this.studentSet = studentSet;
}
public String toString(){
return "StudentSet["+"studentSet="+studentSet+"]";
}
}
private Set<StudentModel> studentSet: Set集合作为属性,实现数据绑定。
Set和List的区别在于Set需要初始化,保证集合中对象的个数足够接收客户端传递过来的参数,否则报错。
Set集合没有索引值,里面的数据是无序的,这里的索引值只起到计数的作用。从结果来看,Set集合创建了3个对象,虽然我们只对索引值为0和2的对象进行了赋值,但索引值为1的对象也被创建了。
3.Map
@Controller
@RequestMapping("/example6/mapController")
public class MapController {
@RequestMapping("/bindMap.htm")
public String bindMap(Model model,StudentMap students){
model.addAttribute("msg", students.toString());
return "/example6/result";
}
}
public class StudentMap {
//StudentModel的Map集合
private Map<String,StudentModel> studentMap;
public Map<String, StudentModel> getStudentMap() {
return studentMap;
}
public void setStudentMap(Map<String, StudentModel> studentMap) {
this.studentMap = studentMap;
}
public String toString(){
return "StudentMap"+"studentMap="+studentMap+"]";
}
}
studentMap[key1].name=jj: 键是key1,对应StudentModel对象的name属性为jj