ZetCode

JSTL forEach 标签

最后修改于 2020 年 7 月 13 日

JSTL forEach 教程展示了如何使用 JSTL 库中的 forEach 标签。

JSTL

JavaServer Pages 标准标签库 (JSTL) 是一个有用的 JSP 标签集合,它为许多 JSP 应用程序提供了核心的通用功能。

forEach 标签

JSTL <c:forEach> 标签是一个基本的迭代标签。它可以遍历各种 Java 集合类型。

<c:forEach> 标签包含以下属性

forEach 标签库声明

<c:forEach> 标签属于 JSTL 核心标签。

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

要使用该标签,我们需要包含此声明。

JSTL Maven 构件

要使用 JSTL 库,我们需要以下 Maven 依赖

<dependency>
    <groupId>jstl</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>

forEach 标签示例

以下 JSP 页面包含 <c:forEach> 标签。除了 <c:forEach> 标签,我们还使用 <c:out> 来显示变量。

index.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <c:forEach var="counter" begin="1" end="8">
            <c:out value="${counter}"/>
        </c:forEach>
    </body>
</html>

该示例在输出中显示了 1..8 的值。

forEach 标签示例 II

下一个 JSP 示例读取从链接发送的参数。

index.html
<!DOCTYPE html>
<html>
    <head>
        <title>Start Page</title>
        <meta charset="UTF-8">
    </head>
    <body>
        
        <a href="target.jsp?name=Jane&age=23&occupation=accountant">Show page</a>
        
    </body>
</html>

index.html 页面包含一个链接,该链接将三个参数发送到 target.jsp 页面。

target.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <c:forEach var="par" items="${param}">

            <c:out value="${par.key}"/>: <c:out value="${par.value}"/> <br>

        </c:forEach>
    </body>
</html>

JSP 页面在隐式对象 param 中接收参数,该对象是一个 map。

<c:forEach var="par" items="${param}">

    <c:out value="${par.key}"/>: <c:out value="${par.value}"/> <br>

</c:forEach>

我们遍历这个 map 并打印出键/值对。

forEach 标签示例 III

HTML <select> 是一个提供选项菜单的控件。通过其 multiple 属性,用户可以从该控件中选择多个值。

index.html
<!DOCTYPE html>
<html>
    <head>
        <title>Languages</title>
        <meta charset="UTF-8">
    </head>
    <body>

        <form action="target.jsp">
            <div>Select languages:</div>

            <select name="languages" size="7" multiple="multiple">
                <option value='Ada'>Ada</option>
                <option value='C'>C</option>
                <option value='C++'>C++</option>
                <option value='Cobol'>Cobol</option>
                <option value='Eiffel'>Eiffel</option>
                <option value='Objective-C'>Objective-C</option>
                <option value='Java'>Java</option>
            </select>

            <button type="submit">Submit</button>

        </form>

    </body>
</html>

我们创建一个包含七个值的 <select> 控件。当我们提交表单时,所选的值会被发送到 target.jsp 文件。

target.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Languages</title>
    </head>
    <body>
        <c:forEach items="${paramValues.languages}" var="lang">
            <c:out value="${lang}"/>
        </c:forEach>
    </body>
</html>

来自 <select> 控件的值可以从隐式对象 paramValues 中获得,它是一个 map。键是请求参数名 (languages),值是一个字符串数组。

<c:forEach items="${paramValues.languages}" var="lang">
    <c:out value="${lang}"/>
</c:forEach>

我们遍历该数组并打印其元素。

forEach 标签示例 IV

以下示例在 HTML 表格中显示数据。

index.html
<!DOCTYPE html>
<html>
    <head>
        <title>Start Page</title>
        <meta charset="UTF-8">
    </head>
    <body>
        <p>
            <a href="MyServlet">Show all cities</a>
        </p>
    </body>
</html>

index.html 页面中,我们有一个调用 MyServlet 的链接。该 servlet 使用一个 service 方法加载数据,并分派到 JSP 页面。

com/zetcode/City.java
package com.zetcode.bean;

public class City {
    
    private Long id;
    private String name;
    private int population;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public City(Long id, String name, int population) {
        this.id = id;
        this.name = name;
        this.population = population;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getPopulation() {
        return population;
    }

    public void setPopulation(int population) {
        this.population = population;
    }
}

这是 City 类;它包含 idnamepopulation 属性。

com/zetcode/MyServlet.java
package com.zetcode.web;

import com.zetcode.bean.City;
import com.zetcode.service.CityService;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name = "MyServlet", urlPatterns = {"/MyServlet"})
public class MyServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html;charset=UTF-8");
        
        List<City> cities = CityService.getAllCities();
        
        request.setAttribute("cities", cities);
        
        request.getRequestDispatcher("showCities.jsp").forward(request, response);
    }
}

servlet 使用 CityService.getAllCities 读取数据,用 setAttribute 将列表对象设置为属性,并转发到 showCities.jsp

com/zetcode/CityService.java
package com.zetcode.service;

import com.zetcode.bean.City;
import java.util.ArrayList;
import java.util.List;

public class CityService {
    
    public static List<City> getAllCities() {
    
       List<City> cities = new ArrayList<>();
        
        cities.add(new City(1L, "Bratislava", 432000));
        cities.add(new City(2L, "Budapest", 1759000));
        cities.add(new City(3L, "Prague", 1280000));
        cities.add(new City(4L, "Warsaw", 1748000));
        cities.add(new City(5L, "Los Angeles", 3971000));
        cities.add(new City(6L, "New York", 8550000));
        cities.add(new City(7L, "Edinburgh", 464000));
        cities.add(new City(8L, "Berlin", 3671000));
        
        return cities;
    }
}

getAllCities 方法返回一个城市列表。

showCities.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Cities</title>
    </head>
    <body>
        <h2>Cities</h2>
        
        <table>
            <thead>
                <tr>
                    <th>Id</th>
                    <th>Name</th>
                    <th>Population</th>
                </tr>
            </thead>
            
            <tbody>
                <c:forEach items="${cities}" var="city">
                <tr>
                    <td>${city.id}</td>
                    <td>${city.name}</td>
                    <td>${city.population}</td>
                </tr>
                </c:forEach>   
            </tbody>
        </table>
    </body>
</html>

showCities.jsp 中,我们使用 <c:forEach> 标签在 HTML 表格中显示城市。

<td>${city.id}</td>
<td>${city.name}</td>
<td>${city.population}</td>

使用点运算符从 city 对象中读取属性。

在本教程中,我们介绍了 JSTL 库中的 <c:forEach> 标签。