javaserver pages documents526 javaserver pages documents you can also write tag files in xml syntax....

22
525 13 JavaServer Pages Documents A JSP document is a JSP page written in XML syntax as opposed to the stan- dard syntax described in Chapter 12. Because it is written in XML syntax, a JSP document is also an XML document and therefore gives you all the benefits offered by the XML standard: You can author a JSP document using one of the many XML-aware tools on the market, enabling you to ensure that your JSP document is well- formed XML. You can validate the JSP document against a document type definition (DTD). You can nest and scope namespaces within a JSP document. You can use a JSP document for data interchange between web applica- tions and as part of a compile-time XML pipeline. In addition to these benefits, the XML syntax gives the JSP page author less complexity and more flexibility. For example, a page author can use any XML document as a JSP document. Also, elements in XML syntax can be used in JSP pages written in standard syntax, allowing a gradual transition from JSP pages to JSP documents. This chapter gives you details on the benefits of JSP documents and uses a sim- ple example to show you how easy it is to create a JSP document.

Upload: others

Post on 28-Jul-2020

12 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: JavaServer Pages Documents526 JAVASERVER PAGES DOCUMENTS You can also write tag files in XML syntax. This chapter covers only JSP docu-ments. Writing tag files in XML syntax will be

525

13JavaServer Pages

Documents

A JSP document is a JSP page written in XML syntax as opposed to the stan-dard syntax described in Chapter 12. Because it is written in XML syntax, a JSPdocument is also an XML document and therefore gives you all the benefitsoffered by the XML standard:

• You can author a JSP document using one of the many XML-aware toolson the market, enabling you to ensure that your JSP document is well-formed XML.

• You can validate the JSP document against a document type definition(DTD).

• You can nest and scope namespaces within a JSP document.• You can use a JSP document for data interchange between web applica-

tions and as part of a compile-time XML pipeline.

In addition to these benefits, the XML syntax gives the JSP page author lesscomplexity and more flexibility. For example, a page author can use any XMLdocument as a JSP document. Also, elements in XML syntax can be used in JSPpages written in standard syntax, allowing a gradual transition from JSP pages toJSP documents.

This chapter gives you details on the benefits of JSP documents and uses a sim-ple example to show you how easy it is to create a JSP document.

Page 2: JavaServer Pages Documents526 JAVASERVER PAGES DOCUMENTS You can also write tag files in XML syntax. This chapter covers only JSP docu-ments. Writing tag files in XML syntax will be

526 JAVASERVER PAGES DOCUMENTS

You can also write tag files in XML syntax. This chapter covers only JSP docu-ments. Writing tag files in XML syntax will be addressed in a future release ofthe tutorial.

The Example JSP Document

This chapter uses the Duke’s Bookstore and books applications to demonstratehow to write JSP pages in XML syntax. The JSP pages of the bookstore5 appli-cation use the JSTL XML tags (see XML Tag Library, page 560) to manipulatethe book data from an XML stream. The books application contains the JSP doc-ument books.jspx, which accesses the book data from the database and con-verts it into the XML stream. The bookstore5 application accesses this XMLstream to get the book data.

These applications show how easy it is to generate XML data and stream itbetween web applications. The books application can be considered the applica-tion hosted by the book warehouse’s server. The bookstore5 application can beconsidered the application hosted by the book retailer’s server. In this way, thecustomer of the bookstore web site sees the list of books currently available,according to the warehouse’s database.

The source for the Duke’s Bookstore application is located in the <INSTALL>/j2eetutorial14/examples/web/bookstore5/ directory, which is createdwhen you unzip the tutorial bundle (see About the Examples, page xxxvi). Sam-ple bookstore5.war and books.war files are provided in <INSTALL>/

j2eetutorial14/examples/web/provided-wars/.

To build the Duke’s Bookstore application, follow these steps:

1. Build and package the bookstore common files as described in Duke’sBookstore Examples (page 103).

2. In a terminal window, go to <INSTALL>/j2eetutorial14/examples/web/bookstore5/.

3. Start the Application Server.4. Perform all the operations described in Accessing Databases from Web

Applications (page 104).

To package and deploy the application using asant, follow these steps:

1. Run asant create-bookstore-war.2. Run asant deploy-war.

Page 3: JavaServer Pages Documents526 JAVASERVER PAGES DOCUMENTS You can also write tag files in XML syntax. This chapter covers only JSP docu-ments. Writing tag files in XML syntax will be

THE EXAMPLE JSP DOCUMENT 527

To learn how to configure the application, use deploytool to package anddeploy it:

1. Start deploytool.2. Create a web application called bookstore5 by running the New Web

Application Wizard. Select File→New→Web Component.3. In the New Web Component wizard:

a. In the WAR File screen, select the Create New Stand-Alone WAR Mod-ule radio button.

b. In the War File field, enter <INSTALL>/j2eetutorial14/examples/web/bookstore5/bookstore5.war. The WAR Display Name field willshow bookstore5.

c. In the Context Root field, enter /bookstore5.d. Click Edit Contents. e. In the Edit Contents dialog box, navigate to <INSTALL>/

j2eetutorial14/examples/web/bookstore5/build/. Select every-thing in the build directory and click Add. Click OK.

f. Add the shared bookstore library. Navigate to <INSTALL>/

j2eetutorial14/examples/web/bookstore/dist/. Select book-

store.jar and Click Add.g. Click OK.h. Click Next.i. Select the JSP Page radio button. j. Click Next.k. Select /bookstore.jsp from the JSP Filename combo box. l. Click Finish.

4. Add each of the web components listed in Table 13–1. For each compo-nent:a. Select File→New→Web Component.b. In the WAR File screen, click the Add to Existing WAR Module radio

button. The WAR file contains all the JSP pages, so you do not have toadd any more content.

c. Click Next.d. Select the JSP Page radio button. e. Click Next.f. Select the page from the JSP Filename combo box.

Page 4: JavaServer Pages Documents526 JAVASERVER PAGES DOCUMENTS You can also write tag files in XML syntax. This chapter covers only JSP docu-ments. Writing tag files in XML syntax will be

528 JAVASERVER PAGES DOCUMENTS

g. Click Finish.h. From the tree, select the web component you added.i. Select the Aliases tab.j. Click Add. Enter the alias as shown in Table 13–1.

5. Add the context parameter that specifies the JSTL resource bundle basename.a. Select the bookstore5 WAR file from the tree.b. Select the Context tab. c. Click Add.d. Enter javax.servlet.jsp.jstl.fmt.localizationContext in the

Coded Parameter field.e. Enter messages.BookstoreMessages for the Value field.

6. Add the context parameter that identifies the context path to the XMLstream.a. On the Context tab, again click Add.b. Enter booksURL for the Coded Parameter.c. Enter http://localhost:8080/books/books.jspx in the Value field.

7. Set the prelude and coda for all JSP pages.a. Select the JSP Properties tab.b. Click the Add button next to the Name list.

Table 13–1 Duke’s Bookstore Web Components

Web Component Name JSP Page Component Alias

bookcashier bookcashier.jsp /bookcashier

bookcatalog bookcatalog.jsp /bookcatalog

bookdetails bookdetails.jsp /bookdetails

bookreceipt bookreceipt.jsp /bookreceipt

bookshowcart bookshowcart.jsp /bookshowcart

bookstore bookstore.jsp /bookstore

Page 5: JavaServer Pages Documents526 JAVASERVER PAGES DOCUMENTS You can also write tag files in XML syntax. This chapter covers only JSP docu-ments. Writing tag files in XML syntax will be

THE EXAMPLE JSP DOCUMENT 529

c. Enter bookstore5.d. Click the Add URL button next to the URL Pattern list.e. Enter *.jsp.f. Click the Edit Preludes button next to the Include Preludes list.g. Click Add.h. Enter /template/prelude.jspf.i. Click OK.j. Click the Edit Codas button next to the Include Codas list.k. Click Add.l. Enter /template/coda.jspf.m.Click OK.

8. Select File→Save.9. Deploy the application.

a. Select Tools→Deploy. b. Click OK.c. A pop-up dialog box will display the results of the deployment. Click

Close.

To build the books application, follow these steps:

1. In a terminal window, go to <INSTALL>/j2eetutorial14/examples/web/books/.

2. Run asant build. This target will spawn any necessary compilations andcopy files to the <INSTALL>/j2eetutorial14/examples/web/books/build/ directory.

To package and deploy the application using asant, follow these steps:

1. Run asant create-bookstore-war.2. Run asant deploy-war.

To learn how to configure the application, use deploytool to package anddeploy it:

1. Create a web application called books by running the New Web Compo-nent wizard. Select File→New→Web Component.

2. In the New Web Component wizard:a. In the WAR File screen, select the Create New Stand-Alone WAR Mod-

ule radio button.

Page 6: JavaServer Pages Documents526 JAVASERVER PAGES DOCUMENTS You can also write tag files in XML syntax. This chapter covers only JSP docu-ments. Writing tag files in XML syntax will be

530 JAVASERVER PAGES DOCUMENTS

b. Click Browse and in the file chooser, navigate to <INSTALL>/

j2eetutorial14/examples/web/books/.c. In the File Name field, enter books.d. Click Create Module File. The WAR Display Name field will show

books.e. In the Context Root field, enter /books.f. Click Edit Contents.g. In the Edit Contents dialog box, navigate to <INSTALL>/

j2eetutorial14/examples/web/books/build/. Select the JSP docu-ment books.jspx and the database and listeners directories andclick Add.

h. Add the shared bookstore library. Navigate to <INSTALL>/

j2eetutorial14/examples/build/web/bookstore/dist/. Selectbookstore.jar and click Add. Click OK.

i. Click Next.j. Select the JSP Page radio button. k. Click Next.l. Select /books.jspx from the JSP Filename combo box. m.Click Finish.

3. Identify books.jspx as an XML document.a. Select the JSP Properties tab.b. Click the Add button next to the Name list.c. Enter books.d. Click the Add URL button next to the URL Pattern list.e. Enter *.jspx.f. Select the Is XML Document checkbox.

4. Add the listener class listeners.ContextListener (described in Han-dling Servlet Life-Cycle Events, page 448). a. Select the Event Listeners tab.b. Click Add.c. Select the listeners.ContextListener class from the drop-down

field in the Event Listener Classes pane.

5. Add a resource reference for the database.a. Select the Resource Ref’s tab.

Page 7: JavaServer Pages Documents526 JAVASERVER PAGES DOCUMENTS You can also write tag files in XML syntax. This chapter covers only JSP docu-ments. Writing tag files in XML syntax will be

CREATING A JSP DOCUMENT 531

b. Click Add.c. Enter jdbc/BookDB in the Coded Name field.d. Accept the default type javax.sql.DataSource.e. Accept the default authorization Container.f. Accept the default selected Shareable.g. Enter jdbc/BookDB in the JNDI name field of the Sun-specific Settings

for jdbc/BookDB frame.

6. Select File→Save.7. Deploy the application.

a. Select the books WAR file from the tree.b. Select Tools→Deploy. c. Click OK.d. A pop-up dialog box will display the results of the deployment. Click

Close.

To run the applications, open the bookstore URL http://localhost:8080/bookstore5/bookstore.

Creating a JSP Document

A JSP document is an XML document and therefore must comply with the XMLstandard. Fundamentally, this means that a JSP document must be well formed,meaning that each start tag must have a corresponding end tag and that the docu-ment must have only one root element. In addition, JSP elements included in theJSP document must comply with the XML syntax.

Much of the standard JSP syntax is already XML-compliant, including all thestandard actions. Those elements that are not compliant are summarized in Table13–2 along with the equivalent elements in XML syntax. As you can see, JSPdocuments are not much different from JSP pages. If you know standard JSP

Page 8: JavaServer Pages Documents526 JAVASERVER PAGES DOCUMENTS You can also write tag files in XML syntax. This chapter covers only JSP docu-ments. Writing tag files in XML syntax will be

532 JAVASERVER PAGES DOCUMENTS

syntax, you will find it easy to convert your current JSP pages to XML syntaxand to create new JSP documents.

To illustrate how simple it is to transition from standard syntax to XML syntax,let’s convert a simple JSP page to a JSP document. The standard syntax versionis as follows:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>

<html><head><title>Hello</title></head><body bgcolor="white">

<img src="duke.waving.gif"> <h2>My name is Duke. What is yours?</h2> <form method="get">

<input type="text" name="username" size="25"><p></p><input type="submit" value="Submit"><input type="reset" value="Reset">

</form><jsp:useBean id="userNameBean" class="hello.UserNameBean"

scope="request"/><jsp:setProperty name="userNameBean" property="name"

value="${param.username}" />

Table 13–2 Standard Syntax Versus XML Syntax

Syntax Elements Standard Syntax XML Syntax

Comments <%--.. --%> <!-- .. -->

Declarations <%! ..%> <jsp:declaration> .. </jsp:declaration>

Directives

<%@ include .. %> <jsp:directive.include .. />

<%@ page .. %> <jsp:directive.page .. />

<%@ taglib .. %> xmlns:prefix="tag library URL"

Expressions <%= ..%> <jsp:expression> .. </jsp:expression>

Scriptlets <% ..%> <jsp:scriptlet> .. </jsp:scriptlet>

Page 9: JavaServer Pages Documents526 JAVASERVER PAGES DOCUMENTS You can also write tag files in XML syntax. This chapter covers only JSP docu-ments. Writing tag files in XML syntax will be

CREATING A JSP DOCUMENT 533

<c:if test="${fn:length(userNameBean.name) > 0}" ><%@include file="response.jsp" %>

</c:if></body>

</html>

Here is the same page in XML syntax:

<htmlxmlns:c="http://java.sun.com/jsp/jstl/core"xmlns:fn="http://java.sun.com/jsp/jstl/functions" ><head><title>Hello</title></head><body bgcolor="white" /><img src="duke.waving.gif" /> <h2>My name is Duke. What is yours?</h2> <form method="get">

<input type="text" name="username" size="25" /><p></p><input type="submit" value="Submit" /><input type="reset" value="Reset" />

</form><jsp:useBean id="userNameBean" class="hello.UserNameBean"

scope="request"/><jsp:setProperty name="userNameBean" property="name"

value="${param.username}" /><c:if test="${fn:length(userNameBean.name) gt 0}" >

<jsp:directive.include="response.jsp" /></c:if></body>

</html>

As you can see, a number of constructs that are legal in standard syntax havebeen changed to comply with XML syntax:

• The taglib directives have been removed. Tag libraries are now declaredusing XML namespaces, as shown in the html element.

• The img and input tags did not have matching end tags and have beenmade XML-compliant by the addition of a / to the start tag.

• The > symbol in the EL expression has been replaced with gt.• The include directive has been changed to the XML-compliant

jsp:directive.include tag.With only these few small changes, when you save the file with a .jspx exten-sion, this page is a JSP document.

Page 10: JavaServer Pages Documents526 JAVASERVER PAGES DOCUMENTS You can also write tag files in XML syntax. This chapter covers only JSP docu-ments. Writing tag files in XML syntax will be

534 JAVASERVER PAGES DOCUMENTS

Using the example described in The Example JSP Document (page 526), the restof this chapter gives you more details on how to transition from standard syntaxto XML syntax. It explains how to use XML namespaces to declare tag libraries,include directives, and create static and dynamic content in your JSP documents.It also describes jsp:root and jsp:output, two elements that are used exclu-sively in JSP documents.

Declaring Tag Libraries

This section explains how to use XML namespaces to declare tag libraries.

In standard syntax, the taglib directive declares tag libraries used in a JSP page.Here is an example of a taglib directive:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

This syntax is not allowed in JSP documents. To declare a tag library in a JSPdocument, you use the xmlns attribute, which is used to declare namespacesaccording to the XML standard:

...xmlns:c="http://java.sun.com/jsp/jstl/core"...

The value that identifies the location of the tag library can take three forms:

• A plain URI that is a unique identifier for the tag library. The containertries to match it against any <taglib-uri> elements in the application’sweb.xml file or the <uri> element of tag library descriptors (TLDs) in JARfiles in WEB-INF/lib or TLDs under WEB-INF.

• A URN of the form urn:jsptld:path.• A URN of the form urn:jsptagdir:path.

The URN of the form urn:jsptld:path points to one tag library packaged withthe application:

xmlns:u="urn:jsptld:/WEB-INF/tlds/my.tld"

Page 11: JavaServer Pages Documents526 JAVASERVER PAGES DOCUMENTS You can also write tag files in XML syntax. This chapter covers only JSP docu-ments. Writing tag files in XML syntax will be

DECLARING TAG LIBRARIES 535

The URN of the form urn:jsptagdir:path must start with /WEB-INF/tags/and identifies tag extensions (implemented as tag files) installed in the WEB-INF/tags/ directory or a subdirectory of it:

xmlns:u="urn:jsptagdir:/WEB-INF/tags/mytaglibs/"

You can include the xmlns attribute in any element in your JSP document, just asyou can in an XML document. This capability has many advantages:

• It follows the XML standard, making it easier to use any XML documentas a JSP document.

• It allows you to scope prefixes to an element and override them.• It allows you to use xmlns to declare other namespaces and not just tag

libraries. The books.jspx page declares the tag libraries it uses with the xmlns attributesin the root element, books:

<booksxmlns:jsp="http://java.sun.com/JSP/Page"xmlns:c="http://java.sun.com/jsp/jstl/core"

>

In this way, all elements within the books element have access to these taglibraries.

As an alternative, you can scope the namespaces:

<books>...

<jsp:useBean xmlns:jsp="http://java.sun.com/JSP/Page"id="bookDB" class="database.BookDB" scope="page">

<jsp:setProperty name="bookDB" property="database" value="${bookDBAO}" />

</jsp:useBean><c:forEach xmlns:c="http://java.sun.com/jsp/jstl/core"

var="book" begin="0" items="${bookDB.books}">...

</c:forEach></books>

Page 12: JavaServer Pages Documents526 JAVASERVER PAGES DOCUMENTS You can also write tag files in XML syntax. This chapter covers only JSP docu-ments. Writing tag files in XML syntax will be

536 JAVASERVER PAGES DOCUMENTS

In this way, the tag library referenced by the jsp prefix is available only to thejsp:useBean element and its subelements. Similarly, the tag library referencedby the c prefix is only available to the c:forEach element.

Scoping the namespaces also allows you to override the prefix. For example, inanother part of the page, you could bind the c prefix to a different namespace ortag library. In contrast, the jsp prefix must always be bound to the JSPnamespace: http://java.sun.com/JSP/Page.

Including Directives in a JSP Document

Directives are elements that relay messages to the JSP container and affect howit compiles the JSP page. The directives themselves do not appear in the XMLoutput.

There are three directives: include, page, and taglib. The taglib directive iscovered in the preceding section.

The jsp:directive.page element defines a number of page-dependent proper-ties and communicates these to the JSP container. This element must be a childof the root element. Its syntax is

<jsp:directive.page page_directive_attr_list />

The page_directive_attr_list is the same list of attributes that the <@ page...> directive has. These are described in Chapter 12. All the attributes areoptional. Except for the import and pageEncoding attributes, there can be onlyone instance of each attribute in an element, but an element can contain morethan one attribute.

An example of a page directive is one that tells the JSP container to load an errorpage when it throws an exception. You can add this error page directive to thebooks.jspx page:

<books xmlns:jsp="http://java.sun.com/JSP/Page"><jsp:directive.page errorPage="errorpage.jsp" />...

</books>

If there is an error when you try to execute the page (perhaps when you want tosee the XML output of books.jspx), the error page is accessed.

Page 13: JavaServer Pages Documents526 JAVASERVER PAGES DOCUMENTS You can also write tag files in XML syntax. This chapter covers only JSP docu-ments. Writing tag files in XML syntax will be

CREATING STATIC AND DYNAMIC CONTENT 537

The jsp:directive.include element is used to insert the text contained inanother file—either static content or another JSP page—into the including JSPdocument. You can place this element anywhere in a document. Its syntax is:

<jsp:directive.include file="relativeURLspec" />

The XML view of a JSP document does not contain jsp:directive.includeelements; rather the included file is expanded in place. This is done to simplifyvalidation.

Suppose that you want to use an include directive to add a JSP document con-taining magazine data inside the JSP document containing the books data. To dothis, you can add the following include directive to books.jspx, assuming thatmagazines.jspx generates the magazine XML data.

<jsp:root version="2.0" ><books ...>...</books><jsp:directive.include file="magazine.jspx" />

</jsp:root>

Note that jsp:root is required because otherwise books.jspx would have tworoot elements: <books> and <magazines>. The output generated frombooks.jspx will be a sequence of XML documents: one with <books> and theother with <magazines> as its root element.

The output of this example will not be well-formed XML because of the two rootelements, so the client might refuse to process it. However, it is still a legal JSPdocument.

In addition to including JSP documents in JSP documents, you can also includeJSP pages written in standard syntax in JSP documents, and you can include JSPdocuments in JSP pages written in standard syntax. The container detects thepage you are including and parses it as either a standard syntax JSP page or aJSP document and then places it into the XML view for validation.

Creating Static and Dynamic Content

This section explains how to represent static text and dynamic content in a JSPdocument. You can represent static text in a JSP document using uninterpretedXML tags or the jsp:text element. The jsp:text element passes its contentthrough to the output.

Page 14: JavaServer Pages Documents526 JAVASERVER PAGES DOCUMENTS You can also write tag files in XML syntax. This chapter covers only JSP docu-ments. Writing tag files in XML syntax will be

538 JAVASERVER PAGES DOCUMENTS

If you use jsp:text, all whitespace is preserved. For example, consider thisexample using XML tags:

<books><book>

Web Servers for Fun and Profit</book>

</books>

The output generated from this XML has all whitespace removed:

<books><book>Web Servers for Fun and Profit

</book></books>

If you wrap the example XML with a <jsp:text> tag, all whitespace is pre-served. The whitespace characters are #x20, #x9, #xD,and #xA.

You can also use jsp:text to output static data that is not well formed. The${counter} expression in the following example would be illegal in a JSP docu-ment if it were not wrapped in a jsp:text tag.

<c:forEach var="counter" begin="1" end="${3}"><jsp:text>${counter}</jsp:text>

</c:forEach>

This example will output

123

The jsp:text tag must not contain any other elements. Therefore, if you need tonest a tag inside jsp:text, you must wrap the tag inside CDATA.

You also need to use CDATA if you need to output some elements that are notwell-formed. The following example requires CDATA wrappers around theblockquote start and end tags because the blockquote element is not well

Page 15: JavaServer Pages Documents526 JAVASERVER PAGES DOCUMENTS You can also write tag files in XML syntax. This chapter covers only JSP docu-ments. Writing tag files in XML syntax will be

CREATING STATIC AND DYNAMIC CONTENT 539

formed. This is because the blockquote element overlaps with other elements inthe example.

<c:forEach var="i" begin="1" end="${x}"><![CDATA[<blockquote>]]>

</c:forEach>...<c:forEach var="i" begin="1" end="${x}">

<![CDATA[</blockquote>]]></c:forEach>

Just like JSP pages, JSP documents can generate dynamic content using expres-sions language (EL) expressions, scripting elements, standard actions, and cus-tom tags. The books.jspx document uses EL expressions and custom tags togenerate the XML book data.

As shown in this snippet from books.jspx, the c:forEach JSTL tag iteratesthrough the list of books and generates the XML data stream. The EL expres-sions access the JavaBeans component, which in turn retrieves the data from thedatabase:

<c:forEach var="book" begin="0" items="${bookDB.books}"><book id="${book.bookId}" >

<surname>${book.surname}</surname><firstname>${book.firstName}</firstname><title>${book.title}</title><price>${book.price}</price><year>${book.year}</year><description>${book.description}</description><inventory>${book.inventory}</inventory>

</book></c:forEach>

When using the expression language in your JSP documents, you must substitutealternative notation for some of the operators so that they will not be interpretedas XML markup. Table 13–3 enumerates the more common operators and theiralternative syntax in JSP documents.

Table 13–3 EL Operators and JSP Document-Compliant Alternative Notation

EL Operator JSP Document Notation

< lt

Page 16: JavaServer Pages Documents526 JAVASERVER PAGES DOCUMENTS You can also write tag files in XML syntax. This chapter covers only JSP docu-ments. Writing tag files in XML syntax will be

540 JAVASERVER PAGES DOCUMENTS

You can also use EL expressions with jsp:element to generate tags dynami-cally rather than hardcode them. This example could be used to generate anHTML header tag with a lang attribute:

<jsp:element name="${content.headerName}" xmlns:jsp="http://java.sun.com/JSP/Page">

<jsp:attribute name="lang">${content.lang}</jsp:attribute><jsp:body>${content.body}</jsp:body>

</jsp:element>

The name attribute identifies the generated tag’s name. The jsp:attribute taggenerates the lang attribute. The body of the jsp:attribute tag identifies thevalue of the lang attribute. The jsp:body tag generates the body of the tag. Theoutput of this example jsp:element could be

<h1 lang="fr">Heading in French</h1>

As shown in Table 13–2, scripting elements (described in Chapter 16) are repre-sented as XML elements when they appear in a JSP document. The only excep-tion is a scriptlet expression used to specify a request-time attribute value.Instead of using <%=expr %>, a JSP document uses %= expr % to represent arequest-time attribute value.

The three scripting elements are declarations, scriptlets, and expressions.

A jsp:declaration element declares a scripting language construct that isavailable to other scripting elements. A jsp:declaration element has noattributes and its body is the declaration itself. Its syntax is

<jsp:declaration> declaration goes here </jsp:declaration>

> gt

<= le

>= ge

!= ne

Table 13–3 EL Operators and JSP Document-Compliant Alternative Notation

EL Operator JSP Document Notation

Page 17: JavaServer Pages Documents526 JAVASERVER PAGES DOCUMENTS You can also write tag files in XML syntax. This chapter covers only JSP docu-ments. Writing tag files in XML syntax will be

USING THE JSP:ROOT ELEMENT 541

A jsp:scriptlet element contains a Java program fragment called a scriptlet.This element has no attributes, and its body is the program fragment that consti-tutes the scriptlet. Its syntax is

<jsp:scriptlet> code fragment goes here </jsp:scriptlet>

The jsp:expression element inserts the value of a scripting language expres-sion, converted into a string, into the data stream returned to the client. Ajsp:expression element has no attributes and its body is the expression. Itssyntax is

<jsp:expression> expression goes here </jsp:expression>

Using the jsp:root Element

The jsp:root element represents the root element of a JSP document. Ajsp:root element is not required for JSP documents. You can specify your ownroot element, enabling you to use any XML document as a JSP document. Theroot element of the books.jspx example JSP document is books.

Although the jsp:root element is not required, it is still useful in these cases:

• When you want to identify the document as a JSP document to the JSPcontainer without having to add any configuration attributes to the deploy-ment descriptor or name the document with a .jspx extension

• When you want to generate—from a single JSP document—more than oneXML document or XML content mixed with non-XML content

The version attribute is the only required attribute of the jsp:root element. Itspecifies the JSP specification version that the JSP document is using.

The jsp:root element can also include xmlns attributes for specifying taglibraries used by the other elements in the page.

The books.jspx page does not need a jsp:root element and therefore doesn’tinclude one. However, suppose that you want to generate two XML documentsfrom books.jspx: one that lists books and another that lists magazines (assum-ing magazines are in the database). This example is similar to the one in the sec-

Page 18: JavaServer Pages Documents526 JAVASERVER PAGES DOCUMENTS You can also write tag files in XML syntax. This chapter covers only JSP docu-ments. Writing tag files in XML syntax will be

542 JAVASERVER PAGES DOCUMENTS

tion Including Directives in a JSP Document (page 536). To do this, you can usethis jsp:root element:

<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.0" ><books>...</books><magazines>...</magazines>

</jsp:root>

Notice in this example that jsp:root defines the JSP namespace because boththe books and the magazines elements use the elements defined in thisnamespace.

Using the jsp:output Element

The jsp:output element specifies the XML declaration or the document typedeclaration in the request output of the JSP document. For more information onthe XML declaration, see The XML Prolog (page 36). For more information onthe document type declaration, see Referencing the DTD (page 58).

The XML declaration and document type declaration that are declared by thejsp:output element are not interpreted by the JSP container. Instead, the con-tainer simply directs them to the request output.

To illustrate this, here is an example of specifying a document type declarationwith jsp:output:

<jsp:output doctype-root-element="books"doctype-system="books.dtd" />

The resulting output is:

<!DOCTYPE books SYSTEM "books.dtd" >

Specifying the document type declaration in the jsp:output element will notcause the JSP container to validate the JSP document against the books.dtd.

If you want the JSP document to be validated against the DTD, you must manu-ally include the document type declaration within the JSP document, just as youwould with any XML document.

Table 13–4 shows all the jsp:output attributes. They are all optional, but someattributes depend on other attributes occurring in the same jsp:output element,

Page 19: JavaServer Pages Documents526 JAVASERVER PAGES DOCUMENTS You can also write tag files in XML syntax. This chapter covers only JSP docu-ments. Writing tag files in XML syntax will be

USING THE JSP:OUTPUT ELEMENT 543

as shown in the table. The rest of this section explains more about usingjsp:output to generate an XML declaration and a document type declaration.

Generating XML Declarations

Here is an example of an XML declaration:

<?xml version="1.0" encoding="UTF-8" ?>

This declaration is the default XML declaration. It means that if the JSP con-tainer is generating an XML declaration, this is what the JSP container willinclude in the output of your JSP document.

Neither a JSP document nor its request output is required to have an XML decla-ration. In fact, if the JSP document is not producing XML output then itshouldn’t have an XML declaration.

The JSP container will not include the XML declaration in the output wheneither of the following is true:

• You set the omit-xml-declaration attribute of the jsp:output elementto either true or yes.

• You have a jsp:root element in your JSP document, and you do not spec-ify omit-xml-declaration="false" in jsp:output.

Table 13–4 jsp:output Attributes

Attribute What It Specifies

omit-xml-declarationA value of true or yes omits the XML declaration. A value of false or no generates an XML declaration.

doctype-root-element

Indicates the root element of the XML document in the DOCTYPE. Can be specified only if doctype-system is specified.

doctype-systemSpecifies that a DOCTYPE is generated in output and gives the SYSTEM literal.

doctype-public

Specifies the value for the Public ID of the generated DOCTYPE. Can be specified only if doctype-system is specified.

Page 20: JavaServer Pages Documents526 JAVASERVER PAGES DOCUMENTS You can also write tag files in XML syntax. This chapter covers only JSP docu-ments. Writing tag files in XML syntax will be

544 JAVASERVER PAGES DOCUMENTS

The JSP container will include the XML declaration in the output when either ofthe following is true:

• You set the omit-xml-declaration attribute of the jsp:output elementto either false or no.

• You do not have a jsp:root action in your JSP document, and you do notspecify the omit-xml-declaration attribute in jsp:output.

The books.jspx JSP document does not include a jsp:root action nor ajsp:output. Therefore, the default XML declaration is generated in the output.

Generating a Document Type Declaration

A document type declaration (DTD) defines the structural rules for the XMLdocument in which the document type declaration occurs. XML documents arenot required to have a DTD associated with them. In fact, the books exampledoes not include one.

This section shows you how to use the jsp:output element to add a documenttype declaration to the XML output of books.jspx. It also shows you how toenter the document type declaration manually into books.jspx so that the JSPcontainer will interpret it and validate the document against the DTD.

As shown in Table 13–4, the jsp:output element has three attributes that youuse to generate the document type declaration:

• doctype-root-element: Indicates the root element of the XML docu-ment

• doctype-system: Indicates the URI reference to the DTD• doctype-public: A more flexible way to reference the DTD. This identi-

fier gives more information about the DTD without giving a specific loca-tion. A public identifier resolves to the same actual document on anysystem even though the location of that document on each system mayvary. See the XML 1.0 specification for more information.

The rules for using the attributes are as follows:

• The doctype attributes can appear in any order• The doctype-root attribute must be specified if the doctype-system

attribute is specified• The doctype-public attribute must not be specified unless doctype-sys-

tem is specified

Page 21: JavaServer Pages Documents526 JAVASERVER PAGES DOCUMENTS You can also write tag files in XML syntax. This chapter covers only JSP docu-ments. Writing tag files in XML syntax will be

USING THE JSP:OUTPUT ELEMENT 545

This syntax notation summarizes these rules:

<jsp:output (omit-xmldeclaration="yes"|"no"|"true"|"false"){doctypeDecl} />

doctypeDecl:=(doctype-root-element="rootElement"doctype-public="PublicLiteral"

doctype-system="SystemLiteral")| (doctype-root-element="rootElement"doctype-system="SystemLiteral")

Suppose that you want to reference a DTD, called books.DTD, from the output ofthe books.jspx page. The DTD would look like this:

<!ELEMENT books (book+) ><!ELEMENT book (surname, firstname, title, price, year,

description, inventory) ><!ATTLIST book id CDATA #REQUIRED ><!ELEMENT surname (#PCDATA) ><!ELEMENT firstname (#PCDATA) ><!ELEMENT title (#PCDATA) ><!ELEMENT price (#PCDATA) ><!ELEMENT year (#PCDATA) ><!ELEMENT description (#PCDATA) ><!ELEMENT inventory (#PCDATA) >

To add a document type declaration that references the DTD to the XML requestoutput generated from books.jspx, include this jsp:output element inbooks.jspx:

<jsp:output doctype-root-element="books" doctype-system="books.DTD" />

With this jsp:output action, the JSP container generates this document typedeclaration in the request output:

<!DOCTYPE books SYSTEM "books.DTD" />

The jsp:output need not be located before the root element of the document.The JSP container will automatically place the resulting document type declara-tion before the start of the output of the JSP document.

Note that the JSP container will not interpret anything provided by jsp:output.This means that the JSP container will not validate the XML document againstthe DTD. It only generates the document type declaration in the XML request

Page 22: JavaServer Pages Documents526 JAVASERVER PAGES DOCUMENTS You can also write tag files in XML syntax. This chapter covers only JSP docu-ments. Writing tag files in XML syntax will be

546 JAVASERVER PAGES DOCUMENTS

output. To see the XML output, run http://localhost:8080/books/

books.jspx in your browser after you have updated books.WAR with books.DTDand the jsp:output element. When using some browsers, you might need toview the source of the page to actually see the output.

Directing the document type declaration to output without interpreting it is use-ful in situations when another system receiving the output expects to see it. Forexample, two companies that do business via a web service might use a standardDTD, against which any XML content exchanged between the companies is val-idated by the consumer of the content. The document type declaration tells theconsumer what DTD to use to validate the XML data that it receives.

For the JSP container to validate books.jspx against book.DTD, you must manu-ally include the document type declaration in the books.jspx file rather than usejsp:output. However, you must add definitions for all tags in your DTD,including definitions for standard elements and custom tags, such as jsp:use-Bean and c:forEach. You also must ensure that the DTD is located in the<J2EE_HOME>/domains/domain1/config/ directory so that the JSP containerwill validate the JSP document against the DTD.

Identifying the JSP Document to the Container

A JSP document must be identified as such to the web container so that the con-tainer interprets it as an XML document. There are three ways to do this:

• In your application’s web.xml file, set the is-xml element of the jsp-property-group element to true. Step 3. in The Example JSPDocument (page 526) explains how to do this if you are using deploytoolto build the application WAR file.

• Use a Java Servlet Specification version 2.4 web.xml file and give your JSPdocument the .jspx extension.

• Include a jsp:root element in your JSP document. This method is back-ward-compatible with JSP 1.2.