How do I include other pages using <jsp:include>?

The <jsp:include/> tag is use for including another page fragment of a JSP page into another page. This is useful when you have a common page such as header, footer or a menu that applied to many of all of your pages.

<%@ page contentType="text/html;charset=UTF-8" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <title><jsp:include/> Demo</title>
</head>
<body>
<div id="header">
    <jsp:include page="include/common/header.jsp"/>
</div>

<div id="main">
    Lorem ipsum dolor sit amet, consectetur adipisicing elit,
    sed do eiusmod tempor incididunt ut labore et dolore magna
    aliqua.
</div>

<div id="footer">
    <jsp:include page="include/common/footer.jsp"/>
</div>
</body>
</html>

Here are the page fragment of the header.jsp, footer.jsp and menu.jsp. All of them are placed in the common folder in the same location with the index.jsp file.

header.jsp

<strong><jsp:include/> Demo</strong>
<hr/>
<jsp:include page="menu.jsp"/>

footer.jsp

<hr/>
© 2021 Kode Java Org

menu.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<a href="<c:url value="/index.jsp"/>">HOME</a>

When you access your page (http://localhost:8080/jsp-include-tag.jsp) from the servlet container such as Apache Tomcat you’ll have a complete display of a page that contains header, menu, content and footer.

Here is the directory structure of our example:

.
.
├─ pom.xml
└─ src
   └─ main
      └─ webapp
         ├─ include
         │  └─ common
         │     ├─ footer.jsp
         │     ├─ header.jsp
         │     └─ menu.jsp
         ├─ jsp-include-tag.jsp
         └─ index.jsp

Maven Dependencies

<dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>jstl</artifactId>
  <version>1.2</version>
</dependency>

Maven Central

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.