- 1 <%--
- 2 5.<c:forEach/>用于迭代或循环
- 3 --%>
- 4 <%
- 5 //List集合
- 6 List<Student> list = new ArrayList<Student>();
- 7 list.add(new Student("abc","123"));
- 8 list.add(new Student("def","123"));
- 9 list.add(new Student("ghi","123"));
- 10 list.add(new Student("jkl","123"));
- 11 pageContext.setAttribute("list", list);
- 12 %>
- 13 EL表达式:<br>${list[0]}<br>${list[1]}<br>${list[2]}<br>${list[3]}<br>
- 14 <%--
- 15 begin:从哪个元素开始遍历,从0开始 可以不写
- 16 end:到哪个元素为止 可以不写
- 17 step:增加步长。默认为1 可以不写
- 18 items:需要遍历的数据。(数组|List集合|Map集合),如果是获取域的数据,那么使用EL表达式获取
- 19 var:每个元素名称
- 20 varStatus:当前状态对象。该对象封装当前元素状态信息。例如count属性:表示当前遍历的是哪个元素,从1开始
- 21 --%>
- 22 JSTL标签:<br>
- 23 <c:forEach items="${list}" var="student" varStatus="varStats">
- 24 学生${varStats.count} :${student}<br>
- 25 </c:forEach>
- 26 <hr/>
- 27 <%
- 28 //Map集合
- 29 Map<String,Student> map = new HashMap<String,Student>();
- 30 map.put("001", new Student("eric","1234"));
- 31 map.put("002", new Student("rose","1234"));
- 32 map.put("003", new Student("jacky","1234"));
- 33 pageContext.setAttribute("map", map);
- 34 %>
- 35 EL表达式:<br>${map['001']}<br>${map['002']}<br>${map['003']}<br>
- 36 JSTL标签:<br>
- 37 <%--
- 38 注意:forEach标签遍历Map集合时,把每个Map的对象使用Entry封装,Entry封装键对象和值对象,
- 39 通过getKey()获取键对象,通过getValue()获取值对象
- 40 --%>
- 41 <c:forEach items="${map}" var="entry" varStatus="varStats">
- 42 <%--学生${varStats.count}:${student}<br> --%>
- 43 编号:${entry.key} - 姓名:${entry.value.name} - 密码:${entry.value.password}<br>
- 44 </c:forEach>