如何使用<Integer>动态键访问 JSTL 中的 HashMap<Integer、ArrayList>?



我想在 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 中的 ArrayList,对应于键 9。第一个<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>

最新更新