文章来源:http://blog.csdn.net/honey_claire/article/details/7664165
在JSP的开发中,迭代是经常要使用到的操作。例如,逐行的显示查询的结果等。在早期的JSP中,通常使用Scriptlets来实现Iterator或者Enumeration对象的迭代输出。现在,通过JSTL的迭代标签可以在很大的程度上简化迭代操作。
JSTL所支持的迭代标签有两个,分别是<c:forEach>和<c:forTokens>。在这里介绍的是<c:forEach>标签。
简单点说,<c:forEach>标签的作用就是迭代输出标签内部的内容。它既可以进行固定次数的迭代输出,也可以依据集合中对象的个数来决定迭代的次数。
<c:forEach>标签,需要与el表达式联合使用
</c:forEach>
下面写一下,我做的项目中用到的例子:
分页:
<table>
<tr><th>名字</th><th>说明</th><th>图片预览</th></tr>
<c:forEach items="${data}" var="item">
<tr><td>${item.advertName}</td><td>${item.notes}</td><td><img src="${item.defPath}"/></td></tr>
</c:forEach>
</table>
<ul>
<li><a href='?nowPage=${nowPage-1}'>←上一页</a></li>
<c:forEach varStatus="i" begin="1" end="${sumPage}">
<c:choose>
<c:when test="${nowPage==i.count}">
<li class='disabled'>${i.count}</li>
</c:when>
<c:otherwise>
<li class='active'><a href='?nowPage=${i.count}'>${i.count}</a></li>
</c:otherwise>
</c:choose>
</c:forEach>
<li><a href='?nowPage=${nowPage+1}'>下一页→</a></li>
</ul>
首页展示图片的例子:
迭代后台传过来的list, src的路径要写绝对路径,写成相对路径会报错,有时绝对路径用<c:ulr>来写
<c:forEach items="${lists}" var="item">
<img id="img${i}" height="250" width="500" class="img" src='UploadImages/${item.advertPath}'/>
</c:forEach>
获得下标,其中size是后台传过来的list的长度,此处不能写成end="${list.size}"
<c:forEach begin="1" end="${size}" step="1" varStatus="i">
<li> <a href="http://www.baidu.com/" class="showimg">${i.index}</a></li>
</c:forEach>