7

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?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Sripaul
  • 2,227
  • 9
  • 36
  • 60

1 Answers1

15

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}"/>
Anthony
  • 9,451
  • 9
  • 45
  • 72
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • 3
    I had to add `type` to the attribute, otherwise I got it as a String. i.e `<%@ attribute name="list" type="MyClass" required="true" %>` – Hagai May 06 '15 at 05:56
  • 1
    I was using a set so i needed type="java.util.LinkedHashSet". – jake_astub Jan 28 '16 at 07:27