Skip to content

JSP Includes

October 30, 2010

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:

  • When a JSP page is called, it will be compiled (by the JSP engine) into a Java servlet.
  • 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.
  • The next time the page is requested, the JSP engine executes the already-loaded servlet unless the JSP page has changed, in which case it is automatically recompiled into a servlet and executed.

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"/>

Advertisements
No comments yet

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: