Skip to Main Content
Java Cookbook
book

Java Cookbook

by Ian F. Darwin
June 2001
Intermediate to advanced content levelIntermediate to advanced
888 pages
21h 1m
English
O'Reilly Media, Inc.
Content preview from Java Cookbook

JSP Include/Forward

Problem

You want to write a “page-composite” JSP that includes other pages or passes control to another page.

Solution

Use <jsp:include> or <jsp:forward>.

Discussion

Suppose you have some common HTML code that you want to appear on every page, such as a navigator or header. You could copy it into each HTML and JSP file, but if it changed, you’d have to find all the files that used it and update each of them. It would be much easier to have one copy and include it everywhere you need it. Most webs servers feature such a mechanism already (e.g., server-side includes). However, using JSP’s mechanism has some advantages, such as the ability to attach objects to a request, a topic I’ll explore in Section 18.9.

The basic mechanism is simply to have <jsp:include> with a PAGE attribute naming the page to be included, and end with </jsp:include>. For convenience, you can put the / at the end of the opening tag and omit the closing tag. Much of this syntax is taken from XML namespaces (see Chapter 21). The FLUSH attribute is also required, and it must have the value TRUE; this is to remind you that, once you do an include, the contents of the output are actually written. Therefore, you can no longer do anything that involves sending HTTP headers, such as changing content type or transferring control using an HTTP redirect request. So a full JSP include might look like this:

<H2>News of the day</H2>
<jsp:include page="./news.jsp" flush="true" />

The jsp:forwar d request ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Practical Cloud-Native Java Development with MicroProfile

Practical Cloud-Native Java Development with MicroProfile

Emily Jiang, Andrew McCright, John Alcorn, David Chan, Alasdair Nottingham
Distributed Computing in Java 9

Distributed Computing in Java 9

Raja Malleswara Rao Malleswara Rao Pattamsetti

Publisher Resources

ISBN: 0596001703Supplemental ContentCatalog PageErrata