jspjsp-tagsjspinclude

Highlighting selected tab in nav header, JSP


Building a web app using JSP for the first time, and attempting to make a navigation header to span all my pages, with the current page highlighted.

My understanding is that the way to share a header like this between my pages would be to use a JSP include tag at the top of each of my JSP files to include a file like header.jsp, which contains my header markup.

However I'm not sure how I would approach applying conditional styling to the header, such that only the active tab is highlighted for each URL. I have an idea of how to accomplish this in JavaScript, but my instinct is that it'd be cleaner for this to be accomplished before responding.

Are any of my assumptions so far off base?

If not, what would be the JSP way to accomplish the goal of conditionally applying styling to an html element?

Thanks for any info!


Solution

  • Forget about including..what's better is to create a html tag. Just create a jsp file for the tag, call it header.jsp and design your menu tabs:

    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
    <%@ taglib prefix="sp" uri="http://www.springframework.org/tags"%>
    <%@ attribute name="selectedTab" required="true" rtexprvalue="true" type="java.lang.String"%>
    
    <ul>
    <li <c:if test="${selectedTab eq 'tab1'}">class="selectedClass"</c:if>>Tab 1 </li>
    <li <c:if test="${selectedTab eq 'tab2'}">class="selectedClass"</c:if>>Tab 2 </li>
    </ul>
    

    Then in all your pages use:

    <!DOCTYPE html>
    <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
    <%@ taglib prefix="h" tagdir="/WEB-INF/tags/html"%>
    
    <h:header selectedTab="${selectedTab}" />
    

    Assume your tags reside in the /WEB-INF/tags/html folder.