How to implement dynamic nav without repeating html in multiple JSP / JSTL files

I have this navigation code in several JSP files:

<ul id="nav">
    <li ><a href="/home">Home</a></li>
    <li class="active" ><a href="/bills">Bills</a></li>
    <li ><a href="/invoices">Invoices</a></li>
</ul>

What is the best way to abstract this code and make the activenav element selection programmatic rather than manually defined in html?

+3
source share
1 answer

Use <jsp:include>to add reusable pieces of JSP code.

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

Use JSTL / EL to dynamically control HTML output.

<ul id="nav">
    <c:forEach items="${pages}" var="page">
        <c:set var="active" value="${fn:endsWith(pageContext.request.requestURI, page.url)}" />
        <li class="${active ? 'active' : 'none'}"><a href="${page.url}">${page.name}</a></li>
    </c:forEach>
</ul>

Use the Javabean class to represent a model that can be used in all layers of code.

public class Page {

    private String url;
    private String name;

    // Add/generate getters, setters and other boilerplate.
}

Use ServletContextListenerto preload application data.

@WebListener
public class Config implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent event) {
        List<Page> pages = new ArrayList<Page>();
        pages.add(new Page("/home", "Home"));
        pages.add(new Page("/bills", "Bills"));
        // ...
        event.getServletContext().setAttribute("pages", pages);
    }

    // ...
}
+3

All Articles