I had to figure out how to iterate through a collection with potentially infinite children in a JSP, so I thought I’d make a protip for future reference. Turns out, it was actually pretty easy.
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.
Leave a Reply