6

Is there a library or best-practice way of creating a menu with navigation links using JSTL?

I have 5 links that go on every page. I want the link that points to the current page to be "disabled". I can do this manually but this must be a problem that people have tackled before. I wouldn't be surprised if there is a taglib that handles it but I don't know of it.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Josh Johnson
  • 10,729
  • 12
  • 60
  • 83

1 Answers1

8

You can let JSTL/EL generate HTML/CSS conditionally based on the URL of the requested JSP page. You can get it by ${pageContext.request.servletPath} in EL. Assuming that you have the links in some Map<String, String> in the application scope:

<ul id="menu">
    <c:forEach items="${menu}" var="item">
        <li>
            <c:choose>
                <c:when test="${pageContext.request.servletPath == item.value}">
                    <b>${item.key}</b>
                </c:when>
                <c:otherwise>
                    <a href="${item.value}">${item.key}</a>
                </c:otherwise>
            </c:choose>
        </li>
    </c:forEach>
</ul>

Or when you're just after a CSS class

<ul id="menu">
    <c:forEach items="${menu}" var="item">
        <li><a href="${item.value}" class="${pageContext.request.servletPath == item.value ? 'active' : 'none'}">${item.key}</a></li>
    </c:forEach>
</ul>

You can use <jsp:include> to reuse content in JSP pages. Put the above in its own menu.jsp file and include it as follows:

<jsp:include page="/WEB-INF/menu.jsp" />

The page is placed in WEB-INF folder to prevent direct access.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Beautiful. Would you have any tips to create that list with jstl? I'd prefer not to build it in a scriptlet or controller layer. – Josh Johnson May 08 '11 at 15:24
  • 2
    If it's applicationwide, I'd just use a `ServletContextListener`. In the `contextInitialized()`, create and store the menu by `event.getServletContext().setAttribute("menu", menu)`. It'll be available in EL the usual way. See also this answer for an example http://stackoverflow.com/questions/3468150/using-init-servlet/3468317#3468317 – BalusC May 08 '11 at 15:29