java - 如何访问 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>
循环有效,但第二个循环无效,我不知道为什么。
任何帮助表示赞赏。
解决方案
在您的特定情况下, ${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>
推荐阅读
- reactjs - 映射打字稿参数:绑定元素“联系人”隐式具有“任何”类型.ts
- ios - 如何为已添加在 UIViewController 之上的 tableView 添加自定义单元格?
- cobol - 使用 XML GENERATE 函数调整生成的名称
- python - 将 scipy.quad 与 iε 技巧一起使用:结果不佳
- java - 如何在一个 Spring Boot 应用程序中提供 html 页面和 jaxrs?
- sql - 如何在使用连接的子查询中使用除法?
- typescript - string!.trim() - 这个 (!) 感叹号在这里做什么?
- java - Android 框架无法使用 gomobile 绑定进行编译
- javascript - 是否可以扩展一个类但不能扩展它的超类
- jquery - 输入值始终为 0 并阻止表单验证