umucpw
Last Updated: February 25, 2016
·
2.875K
· peiche

Recursion in a JSP

Say I have an object that contains objects of the same type as children, like so:

public class Box {
    int id;
    String name;
    List<Box> boxList;
}

How do I iterate through its potentially infinite children in the JSP? Simple: have a page include itself. I have two pages, main.jsp and box.jsp.

First, main.jsp will include box.jsp after setting the box list in the request scope:

<c:set var="boxList" value="${boxList}" scope="request" />
<jsp:include page="box.jsp" />

Then, box.jsp iterates over the list and includes itself in order to iterate over its children:

<ul>
    <c:forEach var="box" items="${boxList}">
        <li>
            ${box.name} <!-- or whatever else you want to display -->
            <jsp:include page="box.jsp" />
        </li>
    </c:forEach>
</ul>

Boom. Done.

1 Response
Add your response

17339

It's not recursive

over 1 year ago ·