Generally, the two most common ways of including a JSP inside another JSP are:
1. Using the include directive (Static include)
2. Using jsp:include (Dynamic include)
It is a widely held misconception that both techniques produce the same results and can be used interchangeably. Even though both work well for static contents, for dynamic contents they are very different.
To understand the difference, let us first see how a JSP works.
All JSPs are translated and compiled to a servlet before they are used. Generally, this happens when the first request comes to the JSP (this can be changed to compile all JSPs at the start up). After this, for all subsequent requests to this JSP, this generated servlet does the functioning of the JSP.
Please note that in the subsequent text, for explanation; we have referred to two JSP files as examples – main.jsp (the main JSP file) and sub.jsp (the included JSP file).
The <%@include file="" %> tag will inject the contents of the sub file (sub.jsp) into the JSP containing this tag (main.jsp), as if it were copied and pasted. During the JSP compilation of main.jsp, this file and its included sub.jsp are parsed as a single file, with the same context and constraints, and with the included sub.jsp contents copied and pasted in the place containing this tag. Thus, as you can see, the translated servlet will include all the sub.jsp contents. Once the translation and compilation is complete, the generated servlet will have the entire compiled code of both main.jsp and sub.jsp in it. Therefore, if we change sub.jsp post generating this servlet, the changes will not be reflected in main.jsp till its next compilation.
This include tag is a run-time instruction to the JSP engine – rather than copying the entire code into the current page, a method call is made to sub.jsp from main.jsp. Therefore, even if you change the sub.jsp after main.jsp is converted to a servlet, it will reflect the changes, as the sub.jsp is rendered every time a call to main.jsp is made (even without recompilation of the main.jsp). However, in this case, the pagecontext and other variables will be different for sub.jsp. If you want to pass some elements, you can use