Friday, August 29, 2014

How to create multilevel menu's in JSP using recursion..

There was a requirement where in I need to create multi-level menu's in a JSP

A role has certain set of Privileges.
Each privilege may or may not have child privileges..

Where Privilege has child privileges, it was desired to display a sub menu..

So this is how I have achieved...
First thing you need to know about this is how to create multi level menu's using HTML and CSS.
(http://javakafunda.blogspot.in/2014/08/how-to-create-multi-level-menus-using.html)

and once you learn that you'll have to use recursion in JSP to achieve the above requirement.

I'll just put the core logic here which is the base of this..

Create a parent jsp (lets say LoginSuccess.jsp)

<ul id="nav">
<c:forEach var="role" items="${userDbObject.roles}"> 
  <li><a href="#item1">${role.roleName}</a>
   <ul> 
   <c:forEach var="priv" items="${role.privileges}">
     <c:set value="${priv}" var="myPriv" scope="request"/>
     <jsp:include page="showPrivileges.jsp"/>
   </c:forEach>
   </ul>
 </li>   
</c:forEach>
</ul>


Create a showPrivileges.jsp as follows:

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:if test="${empty myPriv.childPrivileges}">
  <c:set var="url" value="${myPriv.privUrl}" />
  <c:if test="${not empty url}">
   <li><a href="${url}" >${myPriv.privilegeName}</a></li>
  </c:if>
  <c:if test="${empty url}">
   <li><a href="unimplemented.jsp" >unimplemented.jsp</a></li>
  </c:if>
</c:if>
<c:if test="${not empty myPriv.childPrivileges}">
   <li><a href="#" >${myPriv.privilegeName}</a>
    <ul> 
    <c:forEach var="childPriv" items="${myPriv.childPrivileges}">
      <c:set value="${childPriv}" var="myPriv" scope="request"/>
      <jsp:include page="showPrivileges.jsp"/>
    </c:forEach>
    </ul>
   </li>
</c:if>

No comments:

Post a Comment