使用 JSTL forEach 循环填充 JSP table

Populate JSP table with JSTL forEach Loop

我的程序从输入中获取一封电子邮件,并使用 haveibeenpwned API 向用户显示从该电子邮件中发现的所有漏洞。

我想知道如何让 forEach 循环正确填充 table。目前,它只是将每个项目填充到一个 table 行中,并在数据下方添加 table header。我希望 header 位于顶部,并且每个违规行为都位于单独的 table 行中。

这是我的 .jsp 表格,显示 table 和 forEach:

<table class="table">
  <thead>
    <tr>
      <th scope="col">#</th>
      <th scope="col">Breach</th>
    </tr>
  </thead>
  <tbody>
    <c:forEach var="breach" items="${breaches}" varStatus="status">
      <tr>
        <th scope="row">${status.count}</th>
          <td><p>${breach}</p></td>
      </tr>
    </c:forEach>
  </tbody>
</table>

这是我的 servlet,我从中获得了已发现漏洞的 ArrayList:

String json = callPwnedApi(email);

    if (json.startsWith("{") || json.startsWith("[")) {
        Gson gson = new Gson();
        ArrayList<Breach> breaches = gson.fromJson(json, new TypeToken<ArrayList<Breach>>(){}.getType());

        if (!breaches.isEmpty() && breaches.size() > 0) {
            request.setAttribute("breaches", breaches);
        }
    } 

当您 运行 这段代码时,您看到了什么错误或结果? Here 是一篇教程,里面详细讲解了JSTL的使用方法。如那里所述,我认为您需要在 JSTL 表达式中将 breaches 限定为 requestScope.breaches

所以作为 JSTL 的新手,我犯了一个非常简单的错误!

我不知道我需要将 JSTL 库添加到我的项目中,我还需要将此行添加到我的 .jsp 页面:

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

所以在这样做之后,我的 table 完美运行了!希望这最终能帮助刚接触 JSTL 的人!