forEach标签
forEach标签用来循环.
属性:
* var :定义循环变量
* begin :从哪开始
* end :到哪结束
* step :递增
* items :遍历的内容
* varStatus :记录循环变量
代码:
<h1>JSTL的forEach标签</h1> <h3>遍历数组</h3> <% String[] arrs = { "小默", "小房", "美美" }; pageContext.setAttribute("arrs", arrs); %> <!-- 使用增强for for(类型 遍量:循环内容){} --> <!-- for(String name:arrs){} --> <c:forEach var="name" items="${ arrs }"> ${ name } </c:forEach> <h3>遍历List集合</h3> <% List<String> list = new ArrayList<String>(); list.add("苍老师"); list.add("美美老师"); pageContext.setAttribute("list", list); %> <c:forEach var="name" items="${ list }"> ${ name } </c:forEach> <h3>遍历Map结合</h3> <% Map<String,String> map = new HashMap<String,String>(); map.put("aaa", "凤姐"); map.put("bbb", "芙蓉"); map.put("ccc", "如花"); pageContext.setAttribute("map", map); %> <c:forEach var="entry" items="${ map }"> ${ entry.key } --- ${ entry.value } </c:forEach> <h3>遍历对象的集合</h3> <% List<Person> pList = new ArrayList<Person>(); pList.add(new Person("美美",32)); pList.add(new Person("小边",18)); pList.add(new Person("凤姐",28)); pageContext.setAttribute("pList", pList); %> <c:forEach var="p" items="${ pList }"> ${ p.name } --- ${ p.age } </c:forEach> <h3>输出1到10</h3> <c:forEach var="i" begin="1" end="10" step="1"> ${ i } </c:forEach> <h3>从1加到100的和</h3> <c:set var="sum" value="0" scope="page"></c:set> <c:forEach var="i" begin="1" end="100" step="1"> <c:set var="sum" value="${ sum + i }" scope="page"></c:set> </c:forEach> ${ sum } <h3>从100-200遍历 每次递增 3 到第三个数变成红色</h3> <c:forEach var="i" begin="100" end="200" step="3" varStatus="status"> <c:if test="${ status.count % 3 == 0}"> <font color="red">${ i }</font> </c:if> <c:if test="${ status.count % 3 != 0}"> ${ i } </c:if> </c:forEach>