JSP Include Directive

This article is a series of JSP Tutorial. In this article, we will learn how to use JSP include directive with an example.

The JSP include directive is used to include the contents of any resource it may be JSP file, HTML file or text file. The include directive includes the original content of the included resource at page translation time (the JSP page is translated only once so it will be better to include static resource).
The include directive merges the contents of another file at translation time into the .jsp file.

An advantage of include directive

Code Reusability. For example, we can create a separate header.jsp and footer.jsp pages and include in all other pages using include directive. Instead of keeping the same code in each file, just extract common code as a separate file and include in respective places.

The syntax of the include directive

<%@ include file="filename" %>
where filename is an absolute or relative pathname interpreted according to the current servlet context.
Example:

JSP include directive example

Let's create two JSP files named header.jsp and footer.jsp.

header.jsp

<%@page import="java.time.LocalDate"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
    <div>
         <h1> Header Section</h1>
         Today is: <%= LocalDate.now() %>  
    </div>
</body>
</html>

footer.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
     <div>
         <h1> Footer Section</h1>
     </div>
</body>
</html>

index.jsp

Now, let's create the main page named index.jsp. We will use include directive to include header.jsp and footer.jsp in index.jsp page.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
   <body>
        <%@ include file="include/header.jsp" %>
  
            <h1>
               Inside Body Section
           </h1>
 
        <%@ include file="include/footer.jsp" %>
   </body>
</html>
Let's invoke this JSP page from a Web browser, you see the table on a browser:



In the next article, we will learn how to use JSP taglib directive with an example.

Comments