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.
Written by Paul
Related protips
1 Response
It's not recursive
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Html
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#