Java 如何在jsp/jstl中显示HashMap Key
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23890503/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to display HashMap Key in jsp/jstl
提问by Sachin
I am new to JSP/JSTL.
我是 JSP/JSTL 的新手。
I have set a HashMap on request as follows
我已按要求设置了一个 HashMap,如下所示
HashMap <String, Vector> hmUsers = new HashMap<String, Vector>();
HashMap hmUsers = eQSessionListener.getLoggedinUsers();
request.setAttribute("currentLoggedInUsersMap", hmUsers);
I am alerting HashMap in My jsp as follows
我在我的 jsp 中提醒 HashMap 如下
<script> alert("<c:out value = '${currentLoggedInUsersMap}' />"); </script>
All works as per my expectations till now.
到目前为止,一切都按照我的期望工作。
But if I try to get key of this HashMap as follow then nothing is alerted.
但是,如果我尝试按如下方式获取此 HashMap 的键,则不会发出任何警报。
<script> alert("<c:out value = '${currentLoggedInUsersMap.key}' />"); </script>
Is there anything I am going wrong?
我有什么问题吗?
Thanks in advance.
提前致谢。
回答by Braj
This is what you need to iterate the Map in JSP. For more info have a look at JSTL Core c:forEach Tag.
这是在 JSP 中迭代 Map 所需的。有关更多信息,请查看JSTL Core c:forEach Tag。
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:forEach items="${currentLoggedInUsersMap}" var="entry">
Key = ${entry.key}, value = ${entry.value}<br>
</c:forEach>
It's just like a Map.Entry that is used in JAVA as shown below to get the key-value.
就像JAVA中用来获取key-value的Map.Entry一样,如下图。
for (Map.Entry<String, String> entry : currentLoggedInUsersMap.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
}
Read detained description here on How to loop through a HashMap in JSP?
在此处阅读有关如何在 JSP 中循环遍历 HashMap 的滞留描述?
回答by Prasad
You can iterate over hashmap as:
您可以将 hashmap 迭代为:
<c:forEach items="${currentLoggedInUsersMap}" var="usersMap" varStatus="usersMapStatus">
//Key
Key: ${usersMap.key}
//Iterate over values ,assuming vector of strings
<c:forEach items="${usersMap.value}" var="currentLoggedInUserValue" varStatus="valueStatus">
Value: ${currentLoggedInUserValue}
</c:forEach>
</c:forEach>
Here ${usersMap.key} is the list of keys present in the map and ${usersMap.value} is the vector which you have to iterate again in an inner loop as shown above.
这里 ${usersMap.key} 是地图中存在的键列表, ${usersMap.value} 是您必须在内部循环中再次迭代的向量,如上所示。
Make sure to import:
确保导入:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>