我们如何在 JSTL 中迭代 HashMap?

How can we iterate over an HashMap in JSTL?

我需要显示来自 PL SQL table 的数据以进行分配。我将结果作为 HashMap 获取,并将其传递给 JSP 页面。如何在 table 中显示这些数据?我可以像这样在 JSTL 标签内使用 HTML 标签吗?

<c:forEach items="${employees}" var="employee">
  <td>${employee.name}</td>
  <td>${employee.city}</td>
  <td>${employee.salary}</td>
<c:forEach>

或者是否有任何其他技术可以使用 PL SQL 在 JSP 页面中打印 table ???

编辑: 这是我的代码:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
  </head>
  <body>
    <h1>Employee Details</h1>
    <form action="handler" method="post">
        <table>
            <tr>
                <td>Employee ID</td>
                <td>First Name</td>
                <td>Last Name</td>
                <td>Start Date</td>
                <td>End Date</td>
                <td>Salary</td>
                <td>City</td>
                <td>Description</td>
            </tr>
            <c:forEach items="${employees}" var="employee">
            <tr>
                <td>${employee.value.id}</td>
                <td>${employee.value.fName}</td>
                <td>${employee.value.lName}</td>
                <td>${employee.value.startD}</td>
                <td>${employee.value.endD}</td>
                <td>${employee.value.salary}</td>
                <td>${employee.value.city}</td>
                <td>${employee.value.desc}</td>
            </tr>
            </c:forEach>                    
        </table>
    </form>
  </body>
</html>

编辑 2:

这就是我创建 HashMap 的方式:

while (rs.next()) {
  employee = new Employee(
    rs.getString("EMPLOYEEID"),
    rs.getString("FIRST_NAME"),
    rs.getString("LAST_NAME"),
    rs.getString("START_DATE"),
    rs.getString("END_DATE"),
    rs.getString("SALARY"),
    rs.getString("CITY"),
    rs.getString("DESCRIPTION")
  );

  System.out.println(employee.toString());
  employees.put(rs.getString("EMPLOYEEID"), employee);

这是java方法中的HaspMap创建:

Map<String, String> countryList = new HashMap<String, String>();
countryList.put("United States", "Washington DC");
countryList.put("India", "Delhi");
countryList.put("Germany", "Berlin");
countryList.put("France", "Paris");
countryList.put("Italy", "Rome");

HaspMap 中的第一个参数是键,第二个参数是值。现在您需要在 jsp 中访问它,只需使用键和值作为:

<c:forEach var="country" items="${capitalList}">
    Country: ${country.key}  - Capital: ${country.value}
</c:forEach>

就是这样。在您的情况下,您也可以使用键和值在 jsp 中循环。希望这有帮助。

是的,您可以在 JSTL 标签内使用 HTML 标签。这就是如何在 JSP/HTML 中打印 table。

您可能希望每个 employee 都是一行。为此,请不要忘记将 td 包裹在 c:forEach

中的 tr