<jsp:include page = ... ><jsp:include page = ... > and <%@ include file = ... > let you include information from one page in another. What is the difference between them?
- The
<jsp:include page = ... > directive is like a function call from one jsp to another. It is executed (the included page is executed and the html output it generates is included in output of the calling page) each time the calling page is accessed by the client. The <jsp:include page = ... > is most useful for modularizing your program. The called page is executed whenever the calling page is accessed. In the current assignment, I'm asking you to use <jsp:include page = ... >.
- The
<%@ include file = ... > directive is like a macro. The content of the included page is textually embedded in the page that has the <%@ include file = ... > directive. (This is similar to #include in C++ and macros in assembly languages.) It is executed once, when the including page is first used. It is not called every time the including page is accessed. So there is no updating even if the included page changes. The <%@ include file = ... > is useful if you have some jsp code (such as declarations, etc.) that you want to include in multiple pages. The code itself is included in each page that uses it.
Here is an example of using <jsp:include page = ... >.
- Copy this code into a jsp and save it in a file (called
include.jsp) in
the same directory as bgcolor.jsp.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE><JSP:Include ... ></TITLE>
</HEAD>
<BODY bgcolor=lightgreen>
<H2 BORDER=5 ALIGN="CENTER"><JSP:Include ... ></H2>
This page includes the bgColor.jsp page.
<br>
<br>
<table style="border:inset" align=center>
<tr><td>
<jsp:include page="BGColor.jsp" flush="true" />
</td></tr></table>
<br>
<br>
Here we are after the included page.
</BODY>
</HTML>
- Access the
include.jsp file using Tomcat, i.e., http://localhost:8080/.../include.jsp.
- Follow the bgColor.jsp directions.
- If the background color changes, the browser is very lenient.
- Look at the generated html. Notice that it has two <body> tags. The second one overrode the first. In general, you shouldn't count on this.
- It is worth noting that the included
bgColor.jsp page had access to the parameters send to the calling page.