Display a list in a list with a foreach in jsp

江枫思渺然 提交于 2019-12-20 05:58:21

问题


Is it possible to display the elements of a list in a list with a foreach in a jsp?

List<List<String>> elements;

i was thinking something like :

<c:forEach var="charge" items="${customerOfferForm.offersWithCharges.get(0)}">

回答1:


Your syntax will work in EL 2.2 (which is available since Servlet 3.0 containers such as Tomcat 7, Glassfish 3, etc), but not in older versions. You can then use the brace notation [] to get the desired list item by index.

<c:forEach items="${customerOfferForm.offersWithCharges[0]}" var="charge">
    ...
</c:forEach>

You can if necessary use a nested <c:forEach> to display all items.

<c:forEach items="${customerOfferForm.offersWithCharges}" var="offerWithCharges">
    <c:forEach items="${offerWithCharges}" var="charge">
        ...
    </c:forEach>
</c:forEach>

See also:

  • Our EL wiki page



回答2:


How would you do it with Java code? You would have two nested loops, right?

for (List<String> subList : elements) {
    for (String s : subList) {
        System.out.println(s);
    }
}

You'll need the same thing in your JSP:

<c:forEach var="subList" items="${elements}">
    <c:forEach var="s" items="${subList}">
        <c:out value="${s}"/>
    </c:forEach>
</c:forEach>

If you know the size of each sublist, then you may get one element (the first, here) using ${subList[0]} :

<c:forEach var="subList" items="${elements}">
    <c:out value="${subList[0]}"/>
</c:forEach>



回答3:


for(Iterator<String> i = someList.iterator(); i.hasNext(); ) {
  String item = i.next();
  System.out.println(item);
}

List implements the Iterable interface, so the above code should work.



来源:https://stackoverflow.com/questions/8895630/display-a-list-in-a-list-with-a-foreach-in-jsp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!