Include Directive and Include Action

Include Directive and Include Action

In JavaServer Pages (JSP), both the Include Directive (<%@ include %>) and Include Action (<jsp:include />) are used to include content from another resource (such as another JSP file) into a JSP page. However, they have different behaviors and use cases:

1.  Include Directive (<%@ include %>):

  • Static Inclusion:  The content of the included file is inserted at the translation phase, which means the inclusion happens before the JSP page is compiled into a servlet. This is a static inclusion.
  • Single Compilation:  The main JSP and the included file are treated as a single file, resulting in a single translation and compilation.
  • Performance:  Since it occurs at the translation time, it may improve performance slightly for static content as the inclusion happens once during compilation.
  • Scope:  Variables and methods in the included file can directly interact with those in the main JSP because they become part of the same servlet Include Directive and Include Action.

2.  Include Action (<jsp:include />):

  • Dynamic Inclusion:  The content of the included file is inserted at request time, which means the inclusion happens every time the page is requested. This is a dynamic inclusion.
  • Multiple Compilations:  The main JSP and the included file are compiled separately. The included file is compiled and executed at runtime.
  • Performance:  It might be slightly slower than static inclusion for frequently changing content, but it allows for more flexibility as it includes the latest version of the included file with every request.
  • Scope:  The included file runs in its own context. Local variables in the included file are not directly accessible in the main JSP, and vice versa.

Include Directive and Include Action

Example
Java Example
Include Directive (<%@ include %>)

 main.jsp: 
jsp
<%@ include file="header.jsp" %>
<html>
<body>
    <h1>Main Content</h1>
    <%@ include file="footer.jsp" %>
</body>
</html>


 header.jsp: 
jsp
<h1>This is the header</h1>


 footer.jsp: 
jsp
<h1>This is the footer</h1>


  Include Action (<jsp:include />)

 main.jsp: 
jsp
<jsp:include page="header.jsp" />
<html>
<body>
    <h1>Main Content</h1>
    <jsp:include page="footer.jsp" />
</body>
</html>


 header.jsp: 
jsp
<h1>This is the header</h1>


 footer.jsp: 
jsp
<h1>This is the footer</h1>


Explanation Include Directive and Include Action

1.  Include Directive (<%@ include %>):

  • In main.jsp, the header.jsp and footer.jsp content are statically included during the translation phase.
  • The entire content of header.jsp and footer.jsp is merged into main.jsp before compilation.

2.  Include Action (<jsp:include />):

   In main.jsp, the header.jsp and footer.jsp are dynamically included at runtime.    – Each time main.jsp is requested, it dynamically includes the output of header.jsp and footer.jsp

Homepage

Readmore