> 在 JSTL 中使用动态键?,java,jsp,hashmap,jstl"/>

首页 > 解决方案 > 如何访问 HashMap> 在 JSTL 中使用动态键?

问题描述

我想HashMap<Integer, ArrayList<Integer>>在 JSTL 的循环中按键访问 a,但是我尝试的方法不起作用。

我尝试了两种方法,虽然第一种有效,但它违背了使用 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 代码,它可以工作)。

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

任何帮助表示赞赏。

标签: javajsphashmapjstl

解决方案


在您的特定情况下, ${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>

推荐阅读