JSP Includes

There are now three ways to include a JSP file in another JSP file. They are not only different syntactically, but are indeed processed differently.

To better understand the differences of these 3 ways, we need to understand first the life-cycle of a JSP page. There are 2 main engines and phases:

  1. The JSP engine which compiles/translates JSP pages into servlets
  2. The Servlet engine which executes the servlet classes

The life-cycle of a JSP page:

  • The servlet engine then loads the servlet class and executes it to create dynamic HTML to be sent to the browser. The servlet creates any necessary object, and writes any object as a string to the output stream. This response is returned to the browser.

Now going back to the 3 ways of including a JSP page:

1. Include directive
<%@ include file="papaya.jspf" %>

Say main.jsp includes papaya.jspf with an include directive. When main.jsp is compiled into a servlet, the file papaya.jspf is also compiled then included as part of the main servlet.

This option is better to include JSP pages that do not change often.
The benefit is faster performance when viewing the main page (in this example: main.jsp).

2. JSP include action
<jsp:include page="papaya.jspf" flush="true" />

Say main.jsp includes papaya.jspf with the jsp:include action. When main.jsp is compiled into a servlet, the include statement stays as is. Only when we the main servlet is executed then the result of executing papaya servlet is included.

This option is better to include JSP pages that change often, thus reducing the frequency of having to re-compile main.jsp every time papaya.jspf changes. It can also be used to include pages that cannot be determined until runtime.

3. C import tag
<c:import url="papaya.jspf"/>

This tag behaves the same way as a JSP include action, with additional capabilities.
We can use this tag to import content from remote sources, for example:
<c:import url="http://www.external-source.com/papaya.jsp"/>


Add a New Comment