使用 JSTL <c:forEach> 迭代 List 和 Map 的元素;标签 [英] Iterate over elements of List and Map using JSTL <c:forEach> tag

查看:37
本文介绍了使用 JSTL <c:forEach> 迭代 List 和 Map 的元素;标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个 JSF 支持 bean 返回一个 ArrayList 类型的对象,我应该能够使用 来迭代列表中的元素.每个元素都包含一个地图,尽管已经回答了如何通过 JSTL 访问地图内容的问题 此处 中,如果我传递此类地图的数组,则无法找到如何迭代它们并仍然使用 JSTL 访问地图内容.有一些文档提到了简单的迭代器,但没有提到那些项目本身就是地图的迭代器.

If I have a JSF backing bean return an object of type ArrayList, I should be able to use <c:foreach> to iterate over the elements in the list. Each element contains a map and although the question of how to access the map content through JSTL has been answered here, if I pass an array of such maps, I can't find how to iterate over them and still access the map content using JSTL. There's documentation which refers to simple iterators but not to those whose items are themselves maps.

如果有人能给我一个简单的例子来说明如何在 JSP 中迭代 Java 列表,我将不胜感激.标记

If anyone can give me a simple example of how a java List is iterated over in JSP I'd be massively appreciative. Mark

推荐答案

Mark,这已经在您的 上一个主题.但是好吧,又来了:

Mark, this is already answered in your previous topic. But OK, here it is again:

假设${list}指向一个List,则如下

<c:forEach items="${list}" var="item">
    ${item}<br>
</c:forEach>

与普通Java"中的以下内容基本相同:

does basically the same as as following in "normal Java":

for (Object item : list) {
    System.out.println(item);
}

如果你有一个List>,那么下面的

If you have a List<Map<K, V>> instead, then the following

<c:forEach items="${list}" var="map">
    <c:forEach items="${map}" var="entry">
        ${entry.key}<br>
        ${entry.value}<br>
    </c:forEach>
</c:forEach>

与普通Java"中的以下内容基本相同:

does basically the same as as following in "normal Java":

for (Map<K, V> map : list) {
    for (Entry<K, V> entry : map.entrySet()) {
        System.out.println(entry.getKey());
        System.out.println(entry.getValue());
    }
}

keyvalue 在这里不是特殊的方法等等.它们实际上Map.Entry 对象(单击蓝色的 Map.Entry 链接以查看 API 文档).在 EL(表达式语言)中,您可以使用 . 点运算符来访问使用属性名称"的 getter 方法(没有 get 前缀的 getter 方法名称),一切都只是根据Javabean 规范.

The key and value are here not special methods or so. They are actually getter methods of Map.Entry object (click at the blue Map.Entry link to see the API doc). In EL (Expression Language) you can use the . dot operator to access getter methods using "property name" (the getter method name without the get prefix), all just according the Javabean specification.

也就是说,您确实需要清理上一个主题中的答案",因为它们会给问题增加噪音.另请阅读我在您的答案"中发布的评论.

这篇关于使用 JSTL &lt;c:forEach&gt; 迭代 List 和 Map 的元素;标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆