JSP Tag Recursion

Shyam picture Shyam · Nov 7, 2008 · Viewed 11.4k times · Source

I am implementing a tree tag for one of my practice projects, where I would display the contents of a directory in the form of a tree (recursively). I had implemented a similar requirement as a Custom Tag in Java during the pre-JSP2.0 days. Handling a directory needs recursion (to handle the subdirectories)! Is it possible to code this as tag files and can they be used in a recursive manner?

Answer

Kdeveloper picture Kdeveloper · Jul 2, 2010

Here is an example of an recursive tag file that displays from a node all it's children recursivly (used to generate a YUI treeview):

/WEB-INF/tags/nodeTree.tag:

<%@tag description="display the whole nodeTree" pageEncoding="UTF-8"%>
<%@attribute name="node" type="com.myapp.Node" required="true" %>
<%@taglib prefix="template" tagdir="/WEB-INF/tags" %>
<li>${node.name}
<c:if test="${fn:length(node.childs) > 0}">
    <ul>
    <c:forEach var="child" items="${node.childs}">
        <template:nodeTree node="${child}"/>
    </c:forEach>
    </ul>
</c:if>
</li>

This can be used in a regular JSP file like this:

<div id="treeDiv1">
    <ul>
        <c:forEach var="child" items="${actionBean.rootNode.childs}">
            <template:nodeTree node="${child}"/>
        </c:forEach>
    </ul>
</div>