Reusing Content in JSP Pages
The include directive
Preludes and codas
The jsp:include element
An indirect method of content reuse occurs when a tag file is used to define a custom tag that is used by many web applications. Tag files are discussed in the section Encapsulating Reusable Content Using Tag Files in Chapter 8, Custom Tags in JSP Pages.
The include directive is processed when the JSP page is translated into a servlet class. The effect of the directive is to insert the text contained in another file (either static content or another JSP page) into the including JSP page. You would probably use the include directive to include banner content, copyright information, or any chunk of content that you might want to reuse in another page. The syntax for the include directive is as follows:
<%@ include file="filename" %>
For example, all the Duke’s Bookstore application pages could include the file banner.jspf, which contains the banner content, by using the following directive:
<%@ include file="banner.jspf" %>
Another way to do a static include is to use the prelude and coda mechanisms described in Defining Implicit Includes. This is the approach used by the Duke’s Bookstore application.
Because you must put an include directive in each file that reuses the resource referenced by the directive, this approach has its limitations. Preludes and codas can be applied only to the beginnings and ends of pages. For a more flexible approach to building pages out of content chunks, see A Template Tag Library.
The jsp:include element is processed when a JSP page is executed. The include action allows you to include either a static or a dynamic resource in a JSP file. The results of including static and dynamic resources are quite different. If the resource is static, its content is inserted into the calling JSP file. If the resource is dynamic, the request is sent to the included resource, the included page is executed, and then the result is included in the response from the calling JSP page. The syntax for the jsp:include element is:
<jsp:include page="includedPage" />
The hello1 application discussed in Packaging Web Modules uses the following statement to include the page that generates the response: