How to implement a dynamic nav without repeating html in multiple JSP/JSTL files
-
29-10-2019 - |
Question
I have this nav code in multiple 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's the best way to abstract out this code and make the selection of the active
nav element programmatic rather than manually defined in the html?
Solution
Use <jsp:include>
to include reuseable JSP code fragments.
<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 a Javabean class to represent a model which can be used throughout all code layers.
public class Page {
private String url;
private String name;
// Add/generate getters, setters and other boilerplate.
}
Use a ServletContextListener
to preload applicationwide 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);
}
// ...
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow