JSP - Include Directive


The include directive is used to includes 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 XML equivalent of the above syntax as follows:

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


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

Let us define 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() {
<% addCount(); %>
<title>The include Directive Example</title>
<h2>The include Directive Example</h2>
<p>This site has been visited <%= pageCount %> times.</p>

Following is the content of footer.jsp:

<p>Copyright © 2010</p>

Finally here is the content of main.jsp:

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

Now let us keep all these files in root directory and try to access main.jsp. This would display follow result:

The include Directive Example

This site has been visited 1 times.

Thanks for visiting my page.

Copyright © 2010

Try to refresh the main.jsp and you will find page hit counter will keep increasing.

Now its upto your creativity how you design you web pages but my suggestion is to keep dyanamic parts of your website in separate files and then include them in main file so that if tomorrow you need to change a part of your web page you can change it easily.