现在的位置: 首页 > 综合 > 正文

jstl遍历map集合中的list集合方法

2017年12月03日 ⁄ 综合 ⁄ 共 877字 ⁄ 字号 评论关闭

最好的解释都不如例子来的实在,以下就举一个例子描述用法。

目的:显示各个学校的学生

场景:

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了。

抱歉!评论已关闭.