JSP Include Directive 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.
All JSP Examples at JSP Source Code Examples

The syntax of the include directive

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

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:


All JSP Examples at JSP Source Code Examples.

Comments