使用JSTL创建带有导航链接的菜单

Jos*_*son 6 jsp jstl menu

是否有使用JSTL创建带导航链接的菜单的库或最佳实践方法?

我每页都有5个链接.我希望指向当前页面的链接被"禁用".我可以手动执行此操作,但这必须是人们之前处理过的问题.如果有一个taglib处理它但我不知道它,我不会感到惊讶.

Bal*_*usC 8

您可以让JSTL/EL根据所请求的JSP页面的URL有条件地生成HTML/CSS.你可以${pageContext.request.servletPath}在EL中得到它.假设您Map<String, String>在应用程序范围内的某些链接中有链接:

<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>
Run Code Online (Sandbox Code Playgroud)

或者当你刚刚参加CSS课程之后

<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>
Run Code Online (Sandbox Code Playgroud)

您可以使用<jsp:include>在JSP页面中重用内容.将上面的内容放在自己的menu.jsp文件中,并按如下方式包含它:

<jsp:include page="/WEB-INF/menu.jsp" />
Run Code Online (Sandbox Code Playgroud)

该页面放在WEB-INF文件夹中以防止直接访问.

  • 如果它是应用程序范围的,我只使用`ServletContextListener`.在`contextInitialized()`中,通过`event.getServletContext().setAttribute("menu",menu)`创建和存储菜单.它将以通常的方式在EL中使用.有关示例,请参阅此答案http://stackoverflow.com/questions/3468150/using-init-servlet/3468317#3468317 (2认同)