Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to present a recursive collection in JSP

I have a backend service which is returning me an Info object. This Info object has a list of FolderGroup objects which in turn has list of FolderGroup objects and so on.

Basically it is to represent folders and subfolders. But in my JSP page, I would not know till what depth it is present for me to iterate. How can this be handled with JSTL?

like image 978
Sripaul Avatar asked Jan 03 '13 08:01

Sripaul


1 Answers

Create a JSP tag file (WEB-INF/tags/folderGroups.tag) containing the following code:

<%@ attribute name="list" required="true" %>
<%@ taglib tagdir="/WEB-INF/tags" prefix="myTags" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:if test="${!empty list}">
    <ul>
    <c:forEach var="folderGroup" items="${list}">
        <li><c:out value="${folderGroup.name}"/></li>
        <myTags:folderGroups list="${folderGroup.subGroups}"/>
    </c:forEach>
    </ul>
</c:if>

The tag calls itself recursively to generate a folder tree.

And inside your JSP, do

<%@ taglib tagdir="/WEB-INF/tags" prefix="myTags" %>
...
<myTags:folderGroups list="${info.folderGroups}"/>
like image 184
JB Nizet Avatar answered Sep 18 '22 06:09

JB Nizet