<c:forEach/ >标签
遍历1到10
代码演示
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%--
遍历1到10
begin 设置开始的索引
end 设置结束的索引
var 表示循环的变量(也是当前正在遍历到的数据)
for(int i=1;i<10;i++)
--%>
<c:forEach begin="1" end="10" var="i">
${ i }
</c:forEach>
</body>
</html>
遍历数组
代码演示
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%
request.setAttribute("arr",new String[]{"15959440831","15959440832","15959440833"});
%>
<%--
for(Object item:arr)
items 表示遍历的集合
var 表示当前遍历到的数据
--%>
<c:forEach items="${requestScope.arr}" var="item">
${item}
</c:forEach>
</body>
</html>
遍历Map集合
代码演示
<%@ page import="java.util.Map" %>
<%@ page import="java.util.HashMap" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%
Map<String,Object> map=new HashMap<String, Object>();
map.put("key1","value1");
map.put("key2","value2");
map.put("key3","value3");
// for (Map.Entry<String,Object> entry:map.entrySet()) {
// }
request.setAttribute("map",map);
%>
<c:forEach items="${requestScope.map}" var="entry">
${entry}
${entry.key}
${entry.value}
</c:forEach>
</body>
</html>
遍历List集合-----list中存放Student类,有属性:编号,用户名,密码,年龄,电话信息
Student类
package com.tian.pojo;
public class Student {
private Integer id;
private String username;
private String password;
private Integer age;
private String phone;
// get set 无参 有参 toString方法
}
jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page import="java.util.List" %>
<%@ page import="java.util.ArrayList" %>
<%@ page import="com.tian.pojo.Student" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%
List<Student> studentList=new ArrayList<Student>();
for (int i = 1; i < 10; i++) {
studentList.add(new Student(i,"username"+i,"password"+i,18+i,"phone"+i));
}
request.setAttribute("stus",studentList);
%>
<table>
<tr>
<th>编号</th>
<th>用户名</th>
<th>密码</th>
<th>年龄</th>
<th>电话</th>
<th>操作</th>
</tr>
<c:forEach items="${requestScope.stus}" var="stu">
<tr>
<td>${stu.id}</td>
<td>${stu.username}</td>
<td>${stu.password}</td>
<td>${stu.age}</td>
<td>${stu.phone}</td>
<td>操作 、删除</td>
</tr>
</c:forEach>
</table>
</body>
</html>