gpt4 book ai didi

java - 如何使用动态键在 JSTL 中访问 HashMap> ?

转载 作者:行者123 更新时间:2023-12-02 04:16:01 25 4
gpt4 key购买 nike

我想访问HashMap<Integer, ArrayList<Integer>>在JSTL中通过key循环,但我尝试的方法不起作用。

我尝试过两种方法,虽然第一种方法有效,但它违背了使用 HashMap 的目的。我希望能够直接使用 key 访问该值。

<%
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 标记中(我知道这不是最佳实践,但由于某些限制,我试图保持 HashMap 的部分相同,同时将 JSP 页面的所有其他部分转换为 JSTL )。函数 getLocationLevels 返回所需格式的 HashMap,这是有保证的(因为我之前在 scriptlet 中有一个 Java 代码,它有效)。

假设我要访问HashMap中存储的与键9对应的ArrayList。第一个<c:forEach>循环有效,但第二个循环无效,我不明白为什么。

感谢任何帮助。

最佳答案

在您的特定情况下, ${entry.value} 实际上是一个列表,因此您还需要迭代它:

    <c:forEach var="entry" items="${LocationLevels}">
<c:if test="${entry.key == '9'}">
<c:out value="${entry.value}"/>
<c:set var="tempList" value="${entry.value}"/>
</c:if>
</c:forEach>
<c:forEach var="elem" items='${tempList}'>
<c:out value="${elem}"/>
</c:forEach>

关于java - 如何使用动态键在 JSTL 中访问 HashMap<Integer, ArrayList<Integer>> ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56659731/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com