Spring MVC数据绑定(四)

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值