再讲<c:forEach>之前,现讲一下让EL表达式生效的语句
<% @ page isELIgnored="false"%>这句语句在你想让EL表达式生效的情况下,必须要加载jsp中。
<c:forEach>中各个常用属性的解释如下:
items:要遍历的集合,通常用EL表达式表示:pageContext.setAttribute("mylist",list); ${mylist}
var:变量
varStatus:变量的状态 varStatus的属性有index,和count.其中index从0开始数起,count:个数。
下面的代码讲了java中常用的集合:
<%@ page import="java.util.ArrayList" %>
<%@ page import="com.supwisdom.domain.Student" %>
<%@ page import="java.util.HashMap" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%--el表达式生效的语句--%>
<%@page isELIgnored="false" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%--防止调用函数时报错--%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<html>
<body>
<h2>Hello World!</h2>
<%--forEach的用法--%>
<%--用forEach遍历list集合--%>
<%
ArrayList<String> strings = new ArrayList<String>();
strings.add("王昭君");
strings.add("西施");
strings.add("霍去病");
strings.add("杨开慧");
pageContext.setAttribute("ouyangfeng",strings);
%>
<c:forEach var="item" items="${ouyangfeng}" varStatus="status">
<c:out value="${item}"></c:out>
status.index: <c:out value="${status.index}"></c:out>
status.count:<c:out value="${status.count}"></c:out><br>
</c:forEach>
<%--遍历list对象的集合--%>
<%
Student student = new Student();
student.setId(1);
student.setName("zyh");
student.setAge(16);
Student student2 = new Student();
student2.setId(2);
student2.setName("ouyangfeng");
student2.setAge(29);
ArrayList<Student> students = new ArrayList<Student>();
students.add(student);
students.add(student2);
pageContext.setAttribute("plump",students);
%> <c:forEach var="item" items="${plump}">
学生的姓名: <c:out value="${item.name}"></c:out>
学生的年龄: <c:out value="${item.age}"></c:out>
学生的身份证号:<c:out value="${item.id}"></c:out>
<br>
</c:forEach>
<%--遍历list数组集合--%>
<%
ArrayList<String[]> sixi = new ArrayList<String[]>();
String[] str= new String[]{"country","china"};
String[] str2=new String[]{"address","NewYork"};
String[] str3= new String[]{"student","pupil"};
sixi.add(str);
sixi.add(str2);
sixi.add(str3);
pageContext.setAttribute("array",sixi);
%>
<c:forEach var="item" items="${array}">
<c:out value="${item[0]}"></c:out> <%--数组中的第一个元素--%>
<c:out value="${item[1]}"></c:out> <%--数组中的第二个元素--%>
<br>
</c:forEach>
<%--遍历map集合--%>
<%
HashMap<String, String> map = new HashMap<String, String>();
map.put("China","Reservation");
map.put("France","Romantic");
map.put("America","Innovation");
pageContext.setAttribute("hashmap",map);
%>
<c:forEach var="item" items="${hashmap}">
键是:<c:out value="${item.key}"></c:out>
值是:<c:out value="${item.value}"></c:out><br>
</c:forEach>
</body>
</html>
tomcat运行的结果为:
Hello World! 王昭君 status.index: 0 status.count:1
西施 status.index: 1 status.count:2
霍去病 status.index: 2 status.count:3
杨开慧 status.index: 3 status.count:4
学生的姓名: zyh 学生的年龄: 16 学生的身份证号:1
学生的姓名: ouyangfeng 学生的年龄: 29 学生的身份证号:2
country china
address NewYork
student pupil
键是:France 值是:Romantic
键是:America 值是:Innovation
键是:China 值是:Reservation