I am facing problem in using include directive tag in jsp. Please share a working example.


The include directive is used to include a file during the translation phase. This directive tells the container to merge the content of other external files with the current JSP during the translation phase. You may code include directives anywhere in your JSP page.

The general usage form of this directive is as follows −

<%@ include file = "relative url" >

The filename in the include directive is actually a relative URL. If you just specify a filename with no associated path, the JSP compiler assumes that the file is in the same directory as your JSP.

You can write the XML equivalent of the above syntax as follows −

<jsp:directive.include file = "relative url" />

Example

A good example of the include directive is including a common header and footer with multiple pages of content.

Let us define the following three files (a) header.jps, (b)footer.jsp, and (c)main.jsp as follows −

Following is the content of header.jsp

<%!
   int pageCount = 0;
   void addCount() {
      pageCount++;
   }
%>
<% addCount(); %>
<html>
   <head>
      <title>The include Directive Example</title>
   </head>
   <body>
      <center>
         <h2>The include Directive Example</h2>
         <p>This site has been visited <%= pageCount %> times.</p>
      </center>
      <br/><br/>

Following is the content of footer.jsp

      <br/><br/>
      <center>
         <p>Copyright © 2010</p>
      </center>
   </body>
</html>

Finally here is the content of main.jsp

<%@ include file = "header.jsp" %>
   <center>
      <p>Thanks for visiting my page.</p>
   </center>
<%@ include file = "footer.jsp" %>

Let us now keep all these files in the root directory and try to access main.jsp. You will receive the following output −

The include Directive Example

This site has been visited 1 times.

Thanks for visiting my page.

Copyright © 2010

Refresh main.jsp and you will find that the page hit counter keeps increasing.

You can design your webpages based on your creative instincts; it is recommended you keep the dynamic parts of your website in separate files and then include them in the main file. This makes it easy when you need to change a part of your webpage.

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jul-2019

224 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements