核心标签库

<c:forEach>标签

<c:forEach>标签的主要功能为循环控制,可以将集合中的成员进行迭代输出,功能与Iterator接口类似。

【语法】:

<c:forEach [var="每一个对象的属性名称"] items="集合" [varStatus="保存相关成员信息"] [begin="集合的开始输出位置"] [end="集合的结束输出位置"] [step="每次增长的步长"]>
标签体
</c:forEach>

|属性名称|EL支持|描述
| ------------- |:-------------:|
|var|×|用来存放集合中的每一个对象|
|items|√|保存所有的集合,主要是数组、Collection(List、Set)及Map|
|varStatus|×|用于存放当前对象的成员信息|
|begin|√|集合的开始位置,默认从0开始|
|end|√|集合的结束位置,默认为集合的最后一个元素|
|step|√|每次迭代的间隔数,默认为1|

【输出数组】demo_arrays.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://www.weitang.im/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>标题</title>
</head>
<body>
    <%
        String info[] = { "张三", "李四", "王五", "赵六", "Jack", "Rose" };
        pageContext.setAttribute("ref", info);
    %>

    <h3>
        输出全部:
        <c:forEach items="${ref}" var="mem">
        ${mem}、
        </c:forEach>
    </h3>
    <h3>
        输出全部(间隔为2):
        <c:forEach items="${ref}" var="mem" step="2">
        ${mem}、
        </c:forEach>
    </h3>
    <h3>
        输出前两个:
        <c:forEach items="${ref}" var="mem" begin="0" end="1">
        ${mem}、
        </c:forEach>
    </h3>
</body>
</html>

【输出集合】demo_list.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.util.*" %>
<%@ taglib uri="http://www.weitang.im/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>标题</title>
</head>
<body>
    <%
        List<String> all = new ArrayList<String>();
        all.add("张三");
        all.add("李四");
        all.add("Jack");
        all.add("Rose");
        pageContext.setAttribute("info", all);
    %>
    <c:forEach items="${info}" var="mem">
        ${mem}、
    </c:forEach>
</body>
</html>

在使用<c:forEach>输出时,不仅可以输出List,也可以输出Set,即只要是Collection接口的子接口或类都可以输出。

【输出Map集合】demo_map.jsp

<%@page import="java.util.Map"%>
<%@ page import="java.util.*"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://www.weitang.im/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>标题</title>
</head>
<body>
    <%
        Map<String, String> map = new HashMap<String, String>();
        map.put("baidu", "http://www.baidu.com");
        map.put("google", "http://www.google.com");
        map.put("bing", "http://www.bing.com");
        pageContext.setAttribute("ref", map);
    %>
    
    <c:forEach items="${ref }" var="mem">
        <h2>${mem.key} --- ${mem.value}</h2>
    </c:forEach>
</body>
</html>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容