Java 将 <c:forEach> 与 HashMap 一起使用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2210907/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 04:47:22  来源:igfitidea点击:

Use <c:forEach> with HashMap

javajspjstl

提问by jonasespelita

I have a java class that sets an servlet attribute to a HashMap object:

我有一个将 servlet 属性设置为 HashMap 对象的 java 类:

request.setAttribute("types", da.getSecurityTypes());

where requestis an HttpServletRequest Object, and da.getSecurityTypes()returns a HashMap Object.

其中request是一个 HttpServletRequest 对象,并da.getSecurityTypes()返回一个 HashMap 对象。

Is there a way to go through the HashMap collection using c:foreach or some other JSTL tags?

有没有办法使用 c:foreach 或其他一些 JSTL 标签来浏览 HashMap 集合?

I was thinking:

我刚在想:

 <c:forEach var="type" items="${types}">
                 ...
     </c:forEach>

Or if it can't be done, how would one make a custom tag to process this?

或者,如果无法完成,如何制作自定义标签来处理此问题?

Resorting to Java code in my JSP page is be my last resort and I'd like to know if this is possible with JSTL.

在我的 JSP 页面中使用 Java 代码是我最后的选择,我想知道这是否可以使用 JSTL。

Thanks, Jonas.

谢谢,乔纳斯。

采纳答案by skaffman

Yes, this is perfectly acceptable.

是的,这是完全可以接受的。

When you use <c:forEach>to iterate over a Map, each item in the iteration is an instance of Map.Entry. So given your example:

当您用于<c:forEach>迭代 a 时Map,迭代中的每个项目都是 的一个实例Map.Entry。所以给你的例子:

<c:forEach var="type" items="${types}">
   Key is ${type.key}
   Value is ${type.value}
</c:forEach>

回答by daveb

It works, you'll have type.keyand type.valueto play with in the loop.

它有效,您将拥有type.keytype.value在循环中玩耍。