What is the difference between <jsp:include page = ... > and <%@ include file = ... >?

Prasoon picture Prasoon · Oct 24, 2011 · Viewed 224k times · Source

Both tags include the content from one page in another.

So what is the exact difference between these two tags?

Answer

Suhail Gupta picture Suhail Gupta · Mar 19, 2012

In one reusable piece of code I use the directive <%@include file="reuse.html"%> and in the second I use the tag <jsp:include page="reuse.html" />.

Let the code in the reusable file be :

<html>
<head>
    <title>reusable</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
    <img src="candle.gif" height="100" width="50"/> <br />
    <p><b>As the candle burns,so do I</b></p>
</body>

After running both the JSP files you see the same output and think if there was any difference between the directive and the tag. But if you look at the generated servlet of the two JSP files, you will see the difference.Here is what you will see when you use the directive :

out.write("<html>\r\n");
out.write("    <head>\r\n");
out.write("        <title>reusable</title>\r\n");
out.write("        <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\r\n");
out.write("    </head>\r\n");
out.write("    <body>\r\n");
out.write("        <img src=\"candle.gif\" height=\"100\" width=\"50\"/> <br />\r\n");
out.write("        <p><b>As the candle burns,so do I</b></p>\r\n");
out.write("    </body>\r\n");
out.write("</html>\r\n");

and this is what you will see for the used tag in the second JSP file :

org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, "reusable.html", out, false);

So now you know that the include directive inserts the source of reuse.html at translation time but the action tag inserts the response of reuse.html at runtime.

If you think about it, there is an extra performance hit with every action tag (jsp:include file). It means you can guarantee you will always have the latest content, but it increases performance cost.