2. Using the Tutorial Examples 3. Getting Started with Web Applications 5. JavaServer Pages Technology Identifying the JSP Document to the Container 7. JavaServer Pages Standard Tag Library 10. JavaServer Faces Technology 11. Using JavaServer Faces Technology in JSP Pages 12. Developing with JavaServer Faces Technology 13. Creating Custom UI Components 14. Configuring JavaServer Faces Applications 15. Internationalizing and Localizing Web Applications 16. Building Web Services with JAX-WS 17. Binding between XML Schema and Java Classes 19. SOAP with Attachments API for Java 21. Getting Started with Enterprise Beans 23. A Message-Driven Bean Example 24. Introduction to the Java Persistence API 25. Persistence in the Web Tier 26. Persistence in the EJB Tier 27. The Java Persistence Query Language 28. Introduction to Security in the Java EE Platform 29. Securing Java EE Applications 31. The Java Message Service API 32. Java EE Examples Using the JMS API 36. The Coffee Break Application | Creating a JSP DocumentA JSP document is an XML document and therefore must comply withthe XML standard. Fundamentally, this means that a JSP document must be wellformed, meaning that each start tag must have a corresponding end tag andthat the document must have only one root element. In addition, JSP elementsincluded in the JSP document must comply with the XML syntax. Much of the standard JSP syntax is already XML-compliant, including all the standardactions. Those elements that are not compliant are summarized inTable 6-1 along withthe equivalent elements in XML syntax. As you can see, JSP documents arenot much different from JSP pages. If you know standard JSP syntax, youwill find it easy to convert your current JSP pages to XML syntaxand to create new JSP documents. Table 6-1 Standard Syntax Versus XML Syntax
To illustrate how simple it is to transition from standard syntax to XMLsyntax, let’s convert a simple JSP page to a JSP document. Thestandard syntax version is 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 scope="request"/> <jsp:setProperty name="userNameBean" property="name" value="${param.username}" /> <c:if test="${fn:length(userNameBean.name) > 0}" > <%@include file="response.jsp" %> </c:if> </body></html>Here is the same page in XML syntax: <html xmlns: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 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 instandard syntax have been changed to comply with XML syntax:
With only these few small changes, when you save the file witha.jspx extension, this page is a JSP document. Using the example described inThe Example JSP Document, the rest of this chapter givesyou more details on how to transition from standard syntax to 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 describesjsp:root andjsp:output, two elements that are used exclusively in JSP documents. Declaring Tag LibrariesThis section explains how to use XML namespaces to declare tag libraries. In standard syntax, thetaglib directive declares tag libraries used in a JSPpage. Here is an example of ataglib directive: <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> This syntax is not allowed in JSP documents. To declare a tag libraryin a JSP document, you use thexmlns attribute, which is used todeclare namespaces according to the XML standard: ...xmlns:c="http://java.sun.com/jsp/jstl/core"... The value that identifies the location of the tag library can takethree forms:
The URN of the formurn:jsptld:path points to one tag library packaged withthe application: xmlns:u="urn:jsptld:/WEB-INF/tlds/my.tld" The URN of the formurn:jsptagdir:path must start with/WEB-INF/tags/ and identifies tagextensions (implemented as tag files) installed in the/WEB-INF/tags/ directory or a subdirectory ofit: xmlns:u="urn:jsptagdir:/WEB-INF/tags/mytaglibs/" You can include thexmlns attribute in any element in your JSP document,just as you can in an XML document. This capability has many advantages:
Thebooks.jspx page declares the tag libraries it uses with thexmlns attributesin the root element,books: <books xmlns:jsp="http://java.sun.com/JSP/Page" xmlns:c="http://java.sun.com/jsp/jstl/core"> In this way, all elements within thebooks element have access to thesetag libraries. As an alternative, you can scope the namespaces: <books>... <jsp:useBean xmlns:jsp="http://java.sun.com/JSP/Page" 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>In this way, the tag library referenced by thejsp prefix is availableonly to thejsp:useBean element and its subelements. Similarly, the tag library referencedby thec prefix is only available to thec:forEach element. Scoping the namespaces also allows you to override the prefix. For example, inanother part of the page, you could bind thec prefix to adifferent namespace or tag library. In contrast, thejsp prefix must always bebound tohttp://java.sun.com/JSP/Page, the JSP namespace. Including Directives in a JSP DocumentDirectives are elements that relay messages to the JSP container and affect howit compiles the JSP page. The directives themselves do not appear in theXML output. There are three directives:include,page, andtaglib. Thetaglib directive is covered inthe preceding section. Thejsp:directive.page element defines a number of page-dependent properties and communicates these tothe JSP container. This element must be a child of the root element.Its syntax is <jsp:directive.pagepage-directive-attr-list /> Thepage-directive-attr-list is the same list of attributes that the<@ page ...> directive has. Theseare described inChapter 5, JavaServer Pages Technology. All the attributes are optional. Except for theimport andpageEncoding attributes, there can be only one instance of each attributein an element, but an element can contain more than one attribute. An example of a page directive is one that tells the JSPcontainer to load an error page when it throws an exception. You canadd 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 to see the XML output ofbooks.jspx), the error pageis accessed. Thejsp:directive.include element is used to insert the text contained in another file(either static content or another JSP page) into the including JSP document. Youcan place this element anywhere in a document. Its syntax is: <jsp:directive.include file="relativeURLspec" /> The XML view of a JSP document does not containjsp:directive.include elements;rather the included file is expanded in place. This is done to simplifyvalidation. Suppose that you want to use aninclude directive to add a JSPdocument containing magazine data inside the JSP document containing the books data. Todo this, you can add the followinginclude directive tobooks.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 thatjsp:root is required because otherwisebooks.jspx would have two rootelements:<books> and<magazines>. The output generated frombooks.jspx will be a sequenceof XML documents: one with<books> and the other with<magazines> as itsroot element. The output of this example will not be well-formed XML because ofthe two root elements, so the client might refuse to process it. However,it is still a legal JSP document. In addition to including JSP documents in JSP documents, you can also includeJSP pages written in standard syntax in JSP documents, and you can includeJSP documents in JSP pages written in standard syntax. The container detects thepage you are including and parses it as either a standard syntax JSPpage or a JSP document and then places it into the XML viewfor validation. Creating Static and Dynamic ContentThis section explains how to represent static text and dynamic content in aJSP document. You can represent static text in a JSP document using uninterpretedXML tags or thejsp:text element. Thejsp:text element passes its content throughto the output. If you usejsp:text, all white space is preserved. For example, consider this exampleusing XML tags: <books> <book> Web Servers for Fun and Profit </book></books> The output generated from this XML has all white space removed: <books><book> Web Servers for Fun and Profit</book></books> If you wrap the example XML with a<jsp:text> tag, all white spaceis preserved. The white space characters are#x20,#x9,#xD, and#xA. You can also usejsp:text to output static data that is not wellformed. The${counter} expression in the following example would be illegal in aJSP document if it were not wrapped in ajsp:text tag. <c:forEach var="counter" begin="1" end="${3}"> <jsp:text>${counter}</jsp:text></c:forEach>This example will output 123 Thejsp:text tag must not contain any other elements. Therefore, if you needto nest a tag insidejsp:text, you must wrap the tag insideCDATA. You also need to useCDATA if you need to output some elementsthat are not well-formed. The following example requiresCDATA wrappers around theblockquote start and end tags because theblockquote element is not well formed. Thisis because theblockquote element overlaps with other elements in the 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 expressions language(EL) expressions, scripting elements, standard actions, and custom tags. Thebooks.jspx document uses ELexpressions and custom tags to generate the XML book data. As shown in this snippet frombooks.jspx, thec:forEach JSTL tag iteratesthrough the list of books and generates the XML data stream. The ELexpressions access the JavaBeans component, which in turn retrieves the data from thedatabase: <c:forEach var="book" begin="0" items="${bookDB.books}"> <book > <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 substitute alternativenotation for some of the operators so that they will not be interpretedas XML markup.Table 6-2 enumerates the more common operators and their alternative syntaxin JSP documents. Table 6-2 EL Operators and JSP Document-Compliant Alternative Notation
You can also use EL expressions withjsp:element to generate tags dynamicallyrather than hard code them. This example could be used to generate anHTML header tag with alang 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>Thename attribute identifies the generated tag’s name. Thejsp:attribute tag generates thelang attribute. The body of thejsp:attribute tag identifies the value of thelangattribute. Thejsp:body tag generates the body of the tag. The output ofthis examplejsp:element could be <h1 lang="fr">Heading in French</h1> As shown inTable 6-1, scripting elements (described inChapter 9, Scripting in JSP Pages) are represented as XMLelements when they appear in a JSP document. The only exception is ascriptlet expression used to specify a request-time attribute value. Instead of using<%=expr %>,a JSP document uses%= expr % to represent a request-time attribute value. The three scripting elements are declarations, scriptlets, and expressions. Ajsp:declaration element declares a scripting language construct that is available to otherscripting elements. Ajsp:declaration element has no attributes and its body isthe declaration itself. Its syntax is <jsp:declaration> declaration goes here </jsp:declaration> Ajsp:scriptlet element contains a Java program fragment called a scriptlet. This elementhas no attributes, and its body is the program fragment that constitutes thescriptlet. Its syntax is <jsp:scriptlet> code fragment goes here </jsp:scriptlet> Thejsp:expression element inserts the value of a scripting language expression, converted intoa string, into the data stream returned to the client. Ajsp:expression element hasno attributes and its body is the expression. Its syntax is <jsp:expression> expression goes here </jsp:expression> Using thejsp:root ElementThejsp:root element represents the root element of a JSP document. Ajsp:rootelement is not required for JSP documents. You can specify your own rootelement, enabling you to use any XML document as a JSP document. Theroot element of thebooks.jspx example JSP document isbooks. Although thejsp:root element is not required, it is still useful in thesecases:
Theversion attribute is the only required attribute of thejsp:root element. Itspecifies the JSP specification version that the JSP document is using. Thejsp:root element can also includexmlns attributes for specifying tag libraries usedby the other elements in the page. Thebooks.jspx page does not need ajsp:root element and therefore doesn’t includeone. However, suppose that you want to generate two XML documents frombooks.jspx:one that lists books and another that lists magazines (assuming magazines are inthe database). This example is similar to the one in the sectionIncluding Directives in a JSP Document.To do this, you can use thisjsp: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 thatjsp:root defines the JSP namespace because both thebooks and themagazines elements use the elements defined in this namespace. Using thejsp:output ElementThejsp:output element specifies the XML declaration or the document type declaration inthe request output of the JSP document. The XML declaration and document type declaration that are declared by thejsp:outputelement are not interpreted by the JSP container. Instead, the container simply directsthem to the request output. To illustrate this, here is an example of specifying a document type declarationwithjsp: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 thejsp:output element will not cause theJSP container to validate the JSP document against thebooks.dtd. If you want the JSP document to be validated against the DTD, youmust manually include the document type declaration within the JSP document, just asyou would with any XML document. Table 6-3 shows all thejsp:output attributes. They are all optional, but someattributes depend on other attributes occurring in the samejsp:output element, as shown inthe table. The rest of this section explains more about usingjsp:outputto generate an XML declaration and a document type declaration. Table 6-3jsp:output Attributes
Generating XML DeclarationsHere 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 JSPcontainer 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 havean XML declaration. In fact, if the JSP document is not producing XMLoutput then it shouldn’t have an XML declaration. The JSP container willnot include the XML declaration in the output wheneither of the following is true:
The JSP container will include the XML declaration in the output when eitherof the following is true:
Thebooks.jspx JSP document does not include ajsp:root action nor ajsp:output. Therefore, the default XML declaration is generated in the output. Generating a Document Type DeclarationA document type declaration (DTD) defines the structural rules for the XML documentin which the document type declaration occurs. XML documents are not required tohave a DTD associated with them. In fact, thebooks example does notinclude one. This section shows you how to use thejsp:output element to add adocument type declaration to the XML output ofbooks.jspx. It also shows youhow to enter the document type declaration manually intobooks.jspx so thatthe JSP container will interpret it and validate the document against the DTD. As shown inTable 6-3, thejsp:output element has three attributes that youuse to generate the document type declaration:
The rules for using the attributes are as follows:
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, calledbooks.DTD, from the outputof thebooks.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 theXML request output generated frombooks.jspx, include thisjsp:output element inbooks.jspx: <jsp:output doctype-root-element="books" doctype-system="books.DTD" /> With thisjsp:output action, the JSP container generates this document type declaration inthe request output: <!DOCTYPE books SYSTEM "books.DTD" /> Thejsp:output need not be located before the root element of the document.The JSP container will automatically place the resulting document type declaration before thestart of the output of the JSP document. Note that the JSP container will not interpret anything provided byjsp: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 requestoutput. To see the XML output, runhttp://localhost:8080/books/books.jspx in your browser afteryou have updatedbooks.WAR withbooks.DTD and thejsp:output element. When using somebrowsers, you might need to view the source of the page toactually see the output. Directing the document type declaration to output without interpreting it is useful insituations when another system receiving the output expects to see it. For example,two companies that do business by means of a web service might usea standard DTD, against which any XML content exchanged between the companies isvalidated 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 validatebooks.jspx againstbook.DTD, you must manuallyinclude the document type declaration in thebooks.jspx file rather than usejsp:output. However,you must add definitions for all tags in your DTD, including definitions forstandard elements and custom tags, such asjsp:useBean andc:forEach. You alsomust ensure that the DTD is located in thedomain-dir/config/ directory sothat the JSP container will validate the JSP document against the DTD. Copyright © 2010, Oracle and/or its affiliates. All rights reserved.Legal Notices |