c:forEach标签可用于循环,也可用于遍历数组,List,Map集合等
循环输出:
<h1>循环输出1到10</h1>
<table border="1">
<c:forEach begin="1" end="10" var="i">
<tr><td>第${i}行</td></tr>
</c:forEach>
</table>

遍历数组:
<h1>遍历数组</h1>
<% request.setAttribute("arr",new String[]{"234324324","4553545","676577"});%>
<c:forEach items="${requestScope.arr}" var="item">
${item}
</c:forEach>
<hr>

遍历Map集合
<h1>遍历Map集合</h1>
<% Map<String,Object> map=new HashMap<>();
map.put("key1","value1");
map.put("key2","value2");
map.put("key3","value3");
request.setAttribute("map",map);
//for(Map.Entry<String,Object> entry:map.entrySet()){
//}
%>
<c:forEach items="${requestScope.map}" var="item">
${item.key}==>${item.value} <%-- 其实因为EL表达式会找getXx()方法,所以这里写上key就行啦--%>
<br>
</c:forEach>
<br>

遍历List集合
<h1>遍历List集合</h1>
<% List<Student> studentList=new ArrayList<Student>();
for(int i=0;i<10;i++){
studentList.add(new Student(i,"username"+i,"password"+i,18+i,"phonenumber"+i));
}
request.setAttribute("stus",studentList);
%>
<table border="1">
<th>编号</th>
<th>姓名</th>
<th>密码</th>
<th>年龄</th>
<th>电话号码</th>
<th>Status</th>
<c:forEach items="${requestScope.stus}" var="stu" varStatus="status">
<tr><td>${stu.id}</td>
<td>${stu.username}</td>
<td>${stu.password}</td>
<td> ${stu.age}</td>
<td>${stu.phone}</td>
<td>${status}</td>
</tr>
</c:forEach>
</table>

其中,forEach有几个参数
- items表示遍历的集合
- var 表示遍历的数据
- begin表示遍历的开始索引
- end表示结束的索引值
- step表示循环的步长
- varStatus表示当前遍历到的对象的状态
观察发现varStatus的内容为*:javax.servlet.jsp.jstl.core.LoopTagSupport**$*1Status@50ddec00

$符号表示为内部类,即Status为LoopTagSupport的内部类
查找LoopTagSuppo源码中的Status内部类,发现其实现了接口LoopTagStatus

查看LoopTagStatus,有几个方法

- getCurrent()方法,可以获取当前的遍历到的对象信息
- getIndex()方法表示当前遍历到的对象的索引
- getCount()表示当前遍历到的数目
- isFirst()表示是否为第一个遍历的对象
- isLast()表示是否为最后一个变量的对象
- getBegin()获取初始索引
- getEnd()获取末尾索引
- getStep()获取循环的步长
因此该状态参数可以获得以上8种子状态,
而在EL表达式中,对象.xx就会实现.getXx或者.isXx效果
即可以使用status.current,{status.current},status.current,{status.index},${status.count}等获取到需要的子状态
本文详细介绍了c:forEach标签的用法,包括遍历数组、List、Map集合等。讲解了forEach的重要参数,如items、var、begin、end、step以及varStatus。varStatus提供了如getCurrent、getIndex、getCount等方法,用于获取遍历状态信息,在EL表达式中可以方便地获取所需子状态。
1632

被折叠的 条评论
为什么被折叠?



