最好的解釋都不如例子來的實在,以下就舉一個例子描述用法。
目的:顯示各個學校的學生
場景:
1、有一個list集合裏面存有一個對象School,School的bean中有一個id和name屬性,如下
List<School> schs= schoolService.getSchool();
2、有一個map集合,裏面的key是String類型,value是list集合,該list集合存放的是student的bean對象,student的bean中有name和age屬性,如下
Map<String, List<Student>> mapStu = new HashMap<String, List<Student>>();
第一個list和第二個map的關係是,第一個list的bean中id值是第二個map的key值。如下:
for(int i=0; i<schs.size(); i++){
School school = schs.get(i);
//根據school對象獲得students
List<Student> stus= this.getStudents(school); //該方法是通過學校的id查詢學生的方法,在此省略
mapStu.put(school.getId(), stus);
}
後臺到此ok了,只需將schs集合和mapStu集合放到session或者request中返回到jsp中即可。
在jsp中使用jstl進行遍歷
<c:forEach var="sch" items="${schs}">//遍歷學校先
<ul>
<li>學校名稱:${sch.name}</li>
<c:forEach items="${mapStu[sch.id]}" var="stu"> //根據學校的id遍歷學生
<li>學生姓名:${stu.name}</li>
<li>學生年齡:${stu.age}</li>
</c:forEach>
</ul>
</c:forEach>
到此OK了。