遍历数组
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title></title>
</head>
<body>
<%
String[] fruits = {"apple","orange","grape","banana"};
%>
String数组中的元素:
<br>
<c:forEach var="name" items="<%=fruits%>">
${name} <br>
</c:forEach>
</body>
</html>
遍历Map集合
<%@ page import="java.util.Map" %>
<%@ page import="java.util.HashMap" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title></title>
</head>
<body>
<%
Map userMap = new HashMap();
userMap.put("Tom","123");
userMap.put("Lina","123");
userMap.put("Make","123");
%>
Hash Map集合中的元素:<br>
<c:forEach var="entry" items="<%= userMap%>">
${entry.key} ${entry.value} <br>
</c:forEach>
</body>
</html>
在上面两个例子中,我们已经使用<c:forEach>标签做到了循环数组和循环集合
我们在部分遍历的情况下需要指定循环的 次数 起始索引 结束索引
在JSTL的Core标签库中,<c:forEach>标签的begin end step 分别用于指定循环的起始索引、结束索引和步长。
<%@ page import="java.util.List" %>
<%@ page import="java.util.ArrayList" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title></title>
</head>
<body>
colorsList集合(指定迭代范围和步长)<br>
<%
List colorsList = new ArrayList();
colorsList.add("red");
colorsList.add("yellow");
colorsList.add("blue");
colorsList.add("green");
colorsList.add("black");
%>
<c:forEach var="color" items="<%=colorsList%>" begin="1" end="3" step="2">
${color}
</c:forEach>
</body>
</html>