Display a list in a list with a foreach in jsp

后端 未结 3 1002
一整个雨季
一整个雨季 2021-01-26 00:27

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

List> elements;

i was thinking som

相关标签:
3条回答
  • 2021-01-26 00:52

    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>
    
    0 讨论(0)
  • 2021-01-26 00:54
    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.

    0 讨论(0)
  • 2021-01-26 01:15

    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
    0 讨论(0)
提交回复
热议问题