2. Using the Tutorial Examples 3. Getting Started with Web Applications 5. JavaServer Pages Technology 7. JavaServer Pages Standard Tag Library Internationalization Tag Library Further Information about JSTL 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 | Core Tag LibraryTable 7-2 summarizes the core tags, which include those related to variables and flowcontrol, as well as a generic way to access URL-based resources whose contentcan then be included or processed within the JSP page. Table 7-2 Core Tags
Variable Support TagsTheset tag sets the value of an EL variable or the propertyof an EL variable in any of the JSP scopes (page, request, session,or application). If the variable does not already exist, it is created. The JSP EL variable or property can be set either from theattributevalue: <c:set var="foo" scope="session" value="..."/> or from the body of the tag: <c:set var="foo"> ... </c:set> For example, the following sets an EL variable namedbookID with the valueof the request parameter namedRemove: <c:set var="bookId" value="${param.Remove}"/>To remove an EL variable, you use theremove tag. When the bookstore JSPpagetut-install/javaeetutorial5/examples/web/bookstore4/web/books/bookreceipt.jsp is invoked, the shopping session is finished, so thecartsession attribute is removed as follows: <c:remove var="cart" scope="session"/> Thevalue attribute of theset tag can also take a deferred valueexpression (SeeImmediate and Deferred Evaluation Syntax) so that JavaServer Faces component tags can access the valueat the appropriate stage of the page life cycle. JavaServer Faces technology (seeChapter 10, JavaServer Faces Technology) supports a multiphase life cycle, which includes separatephases for rendering components, validating data, updating model values, and performing other tasks.What this means is that any JavaServer Faces component tags that reference thevalue set by theset tag must have access to this value atdifferent phases of the life cycle, not just during the rendering phase. Considerthe following code: <c:set var="bookId" scope="page" value="#{BooksBean.books}"/>...<h:inputText value="#{bookId}"/>...Thevalue attribute of thec:set tag uses a deferred value expression, whichmeans that thebookId variable it references is available not only during therendering phase of the JavaServer Faces life cycle but also during the laterstages of the life cycle. Therefore, whatever value the user enters into thebookId component tag is updated to the external data object during the appropriatestage of the life cycle. If the expression referenced by thevalue attribute used immediate evaluation syntax thenthebookId variable would be available only when the component is rendered duringthe render response phase. This would prevent the value the user enters intothe component from being converted, validated, or updated to the external data objectduring the later phases of the life cycle. Flow Control Tags in the Core Tag LibraryTo execute flow control logic, a page author must generally resort to usingscriptlets. For example, the following scriptlet is used to iterate through a shoppingcart: <% Iterator i = cart.getItems().iterator(); while (i.hasNext()) { ShoppingCartItem item = (ShoppingCartItem)i.next(); ...%> <tr> <td align="right" bgcolor="#ffffff"> ${item.quantity} </td> ...<% } %>Flow control tags eliminate the need for scriptlets. The next two sections haveexamples that demonstrate the conditional and iterator tags. Conditional TagsTheif tag allows the conditional execution of its body according to thevalue of thetest attribute. The following example fromtut-install/javaeetutorial5/examples/web/bookstore4/web/books/bookcatalog.jsp tests whether therequest parameterAdd is empty. If the test evaluates totrue, the pagequeries the database for the book record identified by the request parameter andadds the book to the shopping cart: <c:if test="${!empty param.Add}"> <c:set var="bid" value="${param.Add}"/> <jsp:useBean type="java.lang.String" /> <sql:query var="books" dataSource="${applicationScope.bookDS}"> select * from PUBLIC.books where id = ? <sql:param value="${bid}" /> </sql:query> <c:forEach var="bookRow" begin="0" items="${books.rows}"> <jsp:useBean type="java.util.Map" /> <jsp:useBean scope="page" /> ... <% cart.add(bid, addedBook); %>...</c:if>Thechoose tag performs conditional block execution by the embeddedwhen subtags.It renders the body of the firstwhen tag whose test condition evaluatestotrue. If none of the test conditions of nestedwhen tags evaluatestotrue, then the body of anotherwise tag is evaluated, if present. For example, the following sample code shows how to render text based ona customer’s membership category. <c:choose> <c:when test="${customer.category == ’trial’}" > ... </c:when> <c:when test="${customer.category == ’member’}" > ... </c:when> <c:when test="${customer.category == ’preferred’}" > ... </c:when> <c:otherwise> ... </c:otherwise> </c:choose>Thechoose,when, andotherwise tags can be used to construct anif-then-else statement as follows: <c:choose> <c:when test="${count == 0}" > No records matched your selection. </c:when> <c:otherwise> ${count} records matched your selection. </c:otherwise> </c:choose>Iterator TagsTheforEach tag allows you to iterate over a collection of objects.You specify the collection using theitems attribute, and the current item is availablethrough a variable named by thevar attribute. A large number of collection types are supported byforEach, including all implementationsofjava.util.Collection andjava.util.Map. If theitems attribute is of typejava.util.Map,then the current item will be of typejava.util.Map.Entry, which has thefollowing properties:
Arrays of objects as well as arrays of primitive types (for example,int) are also supported. For arrays of primitive types, the current item forthe iteration is automatically wrapped with its standard wrapper class (for example,Integerforint,Float forfloat, and so on). Implementations ofjava.util.Iterator andjava.util.Enumeration are supported, but they must be usedwith caution.Iterator andEnumeration objects can't be reset, so they shouldnot be used within more than one iteration tag. Finally,java.lang.String objects can beiterated over if the string contains a list of comma-separated values (for example:Monday,Tuesday,Wednesday,Thursday,Friday). Here’s the shopping cart iteration from the preceding section, now with theforEachtag: <c:forEach var="item" items="${sessionScope.cart.items}"> ... <tr> <td align="right" bgcolor="#ffffff"> ${item.quantity} </td> ...</c:forEach>TheforTokens tag is used to iterate over a collection of tokens separatedby a delimiter. Similarly to the value attribute of thec:set tag (seeVariable Support Tags), theitemsattribute offorEach andforTokens can also take a deferred value expression so thatJavaServer Faces tags can be included within these tags. As described inVariable Support Tags, JavaServer Faces technology (seeChapter 10, JavaServer Faces Technology) supports a multiphase lifecycle. Therefore, any JavaServer Faces component tags that are included in theforEachtag or theforTokens tag must have access to the variable referenced by theitems attribute at different phases of the life cycle, not just during therendering phase. Consider the following code: <c:forEach var="book" items="#{BooksBean.books}"> ... <h:inputText value="#{book.quantity}"/> ...</c:forEach>Theitems attribute uses a deferred value expression, which means that thebookvariable it references is available not only during the rendering phase of theJavaServer Faces life cycle but also during the later stages of the lifecycle. Therefore, whatever values the user enters into thequantity component tags areupdated to the external data object during the appropriate stage of the lifecycle. If the expression referenced by theitems attribute used immediate evaluation syntax thenthebook variable would be available only when the component is rendered duringthe render response phase. This would prevent the values the user enters intothe components from being converted, validated, or updated to the external data objectduring the later phases of the life cycle. The JavaServer Faces version ofDuke’s Bookstore includes aforEach tag on itstut-install/javaeetutorial5/examples/web/bookstore4/web/books/bookcatalog.jsp page. URL TagsThejsp:include element provides for the inclusion of static and dynamic resources inthe same context as the current page. However,jsp:include cannot access resourcesthat reside outside the web application, and it causes unnecessary buffering when theresource included is used by another element. In the following example, thetransform element uses the content of the includedresource as the input of its transformation. Thejsp:include element reads thecontent of the response and writes it to the body content of theenclosing transform element, which then rereads exactly the same content. It would bemore efficient if thetransform element could access the input source directly andthereby avoid the buffering involved in the body content of the transform tag. <acme:transform> <jsp:include page="/exec/employeesList"/><acme:transform/> Theimport tag is therefore the simple, generic way to access URL-basedresources, whose content can then be included and or processed within the JSPpage. For example, inXML Tag Library,import is used to read in the XML documentcontaining book information and assign the content to the scoped variablexml: <c:import url="/books.xml" var="xml" /><x:parse doc="${xml}" var="booklist" scope="application" />Theparam tag, analogous to thejsp:param tag (seejsp:param Element), can be usedwithimport to specify request parameters. Session Tracking discusses how an application must rewrite URLs to enable session tracking wheneverthe client turns off cookies. You can use theurl tag to rewriteURLs returned from a JSP page. The tag includes the session ID inthe URL only if cookies are disabled; otherwise, it returns the URL unchanged.Note that this feature requires that the URL berelative. Theurl tagtakesparam subtags to include parameters in the returned URL. For example,tut-install/javaeetutorial5/examples/web/bookstore4/web/books/bookcatalog.jsp rewrites the URL used to add a book to the shoppingcart as follows: <c:url var="url" value="/catalog" > <c:param name="Add" value="${bookId}" /></c:url><p><strong><a href="${url}">Theredirect tag sends an HTTP redirect to the client. Theredirecttag takesparam subtags for including parameters in the returned URL. Miscellaneous TagsThecatch tag provides a complement to the JSP error page mechanism. Itallows page authors to recover gracefully from error conditions that they can control.Actions that are of central importance to a page shouldnot be encapsulated inacatch; in this way their exceptions will propagate instead to an errorpage. Actions with secondary importance to the page should be wrapped in acatch so that they never cause the error page mechanism to be invoked. The exception thrown is stored in the variable identified byvar, which alwayshas page scope. If no exception occurred, the scoped variable identified byvaris removed if it existed. Ifvar is missing, the exception is simplycaught and not saved. Theout tag evaluates an expression and outputs the result of the evaluationto the currentJspWriter object. The syntax and attributes are as follows: <c:out value="value" [escapeXml="{true|false}"] [default="defaultValue"] />If the result of the evaluation is ajava.io.Reader object, then data isfirst read from theReader object and then written into the currentJspWriterobject. The special processing associated withReader objects improves performance when a large amountof data must be read and then written to the response. IfescapeXml is true, the character conversions listed inTable 7-3 are applied. Table 7-3 Character Conversions
Copyright © 2010, Oracle and/or its affiliates. All rights reserved.Legal Notices |