Master java skills

JSP Include Directive

Include directive syntax

<%@ include file="<file-name>"  %>

JSP include directive is used to include a static resource (like content from another html) into the current JSP page at translation time. Source of the included file is embedded into the current JSP page after translation.

Important points about include directive

  1. Include directive is used for including static content
  2. Include directive cannot include dynamic content such as a servlet or another jsp with dynamic content
  3. Include directive is position specific. It means the compiler includes code exactly where include directive is used in the jsp page
  4. JSP compiler will throw an exception if it doesn’t find the included file
  5. Included page cannot change the response status code or set headers. JSP container will ignore any such code.

Include directive example

home.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%@page import="java.util.Random"%>
<html>
   <head>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      <title>Home Page</title>
   </head>
   <body>
      <%@include file="header.html"%>
      <hr />
          
      <h2>Main content area</h2>
      <%!Random r = new Random();%>
      <p>Your lucky number is : <%=r.nextInt(10)%></p>
          
      <hr />
      <%@include file="footer.html"%>
           
   </body>
</html>

header.html

<html>
<body>
	<h1>This is header</h1>
</body>
</html>

footer.html

<html>
<body>
	<h1>This is footer</h1>
</body>
</html>

Output: