If you need to render a tree-like structure here’s a way of implementing recursion in JSP/JSTL:
${node.title}
<div class="children">
<c:forEach var="node" items="${node.children}">
<c:set var="node" value="${node}" scope="request"/>
<jsp:include page="node.jsp"/>
</c:forEach>
</div>The tricky thing is that when you use jsp:include (and for recursion you have to use the dynamic inclusion), normally, you loose all the variables defined in the parent JSP. But if you redefine the variables you need in the “request” scope, then they will be visible in the included JSP too. I assumed that this very JSP is named “node.jsp” and omitted the declarations. Surprisingly, I found neither this nor any other solution on the Web, so I had to invent one.
Thanks for your post on JSP recursion. This is exactly what I was looking for. I needed to generate a tree structure for DHTML flyout menus. I had resigned myself to having to generate the desired html in a custom tag. But the downside to this approach is embedding html in Java and taking the maintenance of the navigation style out of my designer’s hands and placing it in my own. This solution is much more elegant by keeping the html where it belongs.
You are welcome, Andrew! I’m glad to hear it was useful for you.
hi,
if i want to use your code does that mean I need to create a jsp just to house this code and then make my main jsp call this jsp ?
That’s right. I think this is the only possibility to reuse parts of jsp code. You can reuse chunks of generated HTML defining variables with c:set, but not JSP.
Hi.
I’m a newbie to J2EE. Could you explain what do you mean by “redefine the variables you need in the “request” scope”? I have a tree structure which i like to show. Does it mean that i have to fetch the tree structure for every call of node.asp? Or can I “hand over” the (sub)tree structure to each node.jsp?
Thanks for this – you could do with updating your example to use camel case c:forEach
That’s right. I think this is the only possibility to reuse parts of jsp code. You can reuse chunks of generated HTML defining variables with c:set, but not JSP.
Thanks for your post on JSP recursion. This is exactly what I was looking for. I needed to generate a tree structure for DHTML flyout menus. I had resigned myself to having to generate the desired html in a custom tag. But the downside to this approach is embedding html in Java and taking the maintenance of the navigation style out of my designer’s hands and placing it in my own. This solution is much more elegant by keeping the html where it belongs.
this stuff does not work
you get and endless loop because ‘node’ gets overwritten in the inner loop
@Gabor: I think you did something wrong. You shouldn’t get an endless loop exactly because ‘node’ is overwritten.
Thanks very much, it works! It helped me to avoid converting hierarchical structure to linear table!
Hi, thanks for that info, that’s really what i was looking for.
Greetings.