Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a menu with navigation links with JSTL

Tags:

jsp

jstl

menu

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.

like image 662
Josh Johnson Avatar asked May 08 '11 14:05

Josh Johnson


1 Answers

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.

like image 167
BalusC Avatar answered Nov 09 '22 05:11

BalusC