简体   繁体   English

使用JSTL <c:forEach>标记迭代List和Map的元素

[英]Iterate over elements of List and Map using JSTL <c:forEach> tag

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. 如果我有一个JSF支持bean返回一个ArrayList类型的对象,我应该能够使用<c:foreach>迭代列表中的元素。 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. 每个元素都包含一个地图,虽然这里已经回答了如何通过JSTL访问地图内容的问题,如果我传递了这样的地图数组,我找不到如何迭代它们仍然使用JSTL访问地图内容。 There's documentation which refers to simple iterators but not to those whose items are themselves maps. 有文档引用简单的迭代器,但不是那些项目本身就是映射的文档。

If anyone can give me a simple example of how a java List is iterated over in JSP I'd be massively appreciative. 如果有人能给我一个简单的例子来说明如何在JSP中迭代java List我会非常感激。 Mark 标记

Mark, this is already answered in your previous topic . 马克,这已在前一个主题中得到解答。 But OK, here it is again: 但好的,这又是:

Suppose ${list} points to a List<Object> , then the following 假设${list}指向List<Object> ,然后是以下内容

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

does basically the same as as following in "normal Java": 与“普通Java”中的内容基本相同:

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

If you have a List<Map<K, V>> instead, then the following 如果你有一个List<Map<K, V>> ,那么以下

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

does basically the same as as following in "normal Java": 与“普通Java”中的内容基本相同:

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

The key and value are here not special methods or so. keyvalue在这里不是特殊的方法。 They are actually getter methods of Map.Entry object (click at the blue Map.Entry link to see the API doc). 它们实际上Map.Entry对象的getter方法(单击蓝色的Map.Entry链接以查看API文档)。 In EL (Expression Language) you can use the . 在EL(表达式语言)中,您可以使用. dot operator to access getter methods using "property name" (the getter method name without the get prefix), all just according the Javabean specification. 点运算符使用“属性名称”(没有get前缀的getter方法名称)访问getter方法,所有这些都只是根据Javabean规范。

That said, you really need to cleanup the "answers" in your previous topic as they adds noise to the question. 也就是说,你真的需要清理上一个主题中的“答案”,因为它们会给问题增加噪音。 Also read the comments I posted in your "answers". 另请阅读我在“答案”中发布的评论。

try this 试试这个

<c:forEach items="${list}" var="map">
    <tr>
        <c:forEach items="${map}" var="entry">

            <td>${entry.value}</td>

        </c:forEach>
    </tr>
</c:forEach>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM