【发布时间】:2019-11-01 17:23:56
【问题描述】:
我想在 JSTL 的循环中按键访问HashMap<Integer, ArrayList<Integer>>,但我尝试的方法不起作用。
我尝试了两种方法,虽然第一种有效,但它违背了使用 HashMap 的目的。我希望能够通过直接使用密钥来访问值。
<%
HashMap<Integer, ArrayList<Integer>> LocationLevels =
levelManagementBean.getLocationLevels((Integer)
session.getAttribute("NodeId"), (String)
session.getAttribute("NodeName"));
pageContext.setAttribute("LocationLevels", LocationLevels);
%>
<c:forEach items="${LocationLevels}" var="elem">
<c:if test="${elem.key == 9}">
<c:forEach items="${elem.value}" var="levs">
<c:out value="${levs}"/>
</c:forEach>
</c:if>
</c:forEach>
<br>
<c:set var="temp" value="9"/>
<c:forEach var="elem" items="${LocationLevels[temp]}">
<c:out value="${elem}"/>
</c:forEach>
LocationLevels 是从 Bean 函数返回的 HashMap。代码的前两行在 scriptlet 标记中(我知道这不是最佳实践,但由于一些限制,我试图在将 JSP 页面的所有其他部分转换为 JSTL 时保持 HashMap 的部分相同)。函数 getLocationLevels 返回所需格式的 HashMap,这是有保证的(因为我之前在 scriptlet 中有一个 Java 代码,它可以工作)。
假设我想访问存储在 HashMap 中与键 9 相对应的 ArrayList。第一个 <c:forEach> 循环有效,但第二个无效,我不知道为什么。
感谢任何帮助。
【问题讨论】:
-
你遇到了什么错误可以在这里提出
-
<br>标签之前的循环可以正常工作。它显示与该键对应的数组列表的元素。但是<br>标签之后的循环不起作用,它什么都不显示。