Include header and footer in JSP using JSTL

Header and Footer are the common part of every page on any website. There is two way to create a header and footer for any website.

  1. Keep the header and footer code on every page of the website.
  2. Create separate header and footer pages and include them in all the pages of the website.

The second way is a more convenient and time-saving process. so in this article let’s create a simple header and footer page and include them on the home page using JSP and JSTL.

There are 3 ways to include a page into another page in JSP.

  • Include JSP page Using JSTL.
  • Include JSP page Using JSP  directive.
  • By using JSP include directive.

Let’s see all these 3 ways, by and simple example, where we are going to create header and footer page and include them into the home page.

Include header and footer in JSP using JSTL

The core library of JSTL contains <c:import/> tag that is used to import a page into another JSP page.

In the below code, we are using <c:import/> tag with URL attribute and the value of the URL will be the path of the page(header.jsp) or any page that you want to include.

<c:import url="header.jsp" />

Include JSP page Using JSP  directive

Include header in JSP using JSP directive, Add a attribute file=”header.jsp”. The value of the file will be the path of the page that you want to include.

<%@ include file="header.jsp" %>

Include JSP page Using JSP:include directive

Include header in JSP using JSP:include directive, Add a attribute page=”header.jsp”. The value of the file will be the path of the page that you want to include.

<jsp:include page="Header.jsp" />

Include header and footer in JSP

Let’s see all three types in a single example, Create header.jsp, footer.jsp, and body.jsp. Now create page home.jsp and include all these three pages into home.jsp.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<c:import url="header.jsp" />
</head>
<body>

<%@include file="body.jsp"%>

</body>

<footer>
<jsp:include page="footer.jsp" />
</footer>

</html>