Core Tag Library
Table 6-2 summarizes the core tags, which include those related to variables and flow control, as well as a generic way to access URL-based resources whose content can then be included or processed within the JSP page.
Variable Support Tags
The
settag sets the value of an EL variable or the property of 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 the attribute
value:or from the body of the tag:
For example, the following sets an EL variable named
bookIDwith the value of the request parameter namedRemove:To remove an EL variable, you use the
removetag. When the bookstore JSP pagebookreceipt.jspis invoked, the shopping session is finished, so thecartsession attribute is removed as follows:The
valueattribute of thesettag can also take a deferred value expression (See Immediate and Deferred Evaluation Syntax, page 110) so that JavaServer Faces component tags can access the value at the appropriate stage of the page life cycle.JavaServer Faces technology (see Chapter 9) supports a multi-phase life cycle, which includes separate phases for rendering components, validating data, updating model values, and performing other tasks. What this means is that any JavaServer Faces component tags that reference the value set by the
settag must have access to this value at different phases of the life cycle, not just during the rendering phase. Consider the following code:<c:set var="bookId" scope="page" value="#{BooksBean.books}"/> ... <h:inputText id="bookId" value="#{bookId}"/> ...The
valueattribute of the c:set tag uses a deferred value expression, which means that thebookIdvariable it references is available not only during the rendering phase of the JavaServer Faces life cycle but also during the later stages of the life cycle. Therefore, whatever value the user enters into thebookIdcomponent tag is updated to the external data object during the appropriate stage of the life cycle.If the expression referenced by the
valueattribute used immediate evaluation syntax then thebookIdvariable would be available only when the component is rendered during the render response phase. This would prevent the value the user enters into the component from being converted, validated, or updated to the external data object during the later phases of the life cycle.Flow Control Tags
To execute flow control logic, a page author must generally resort to using scriptlets. For example, the following scriptlet is used to iterate through a shopping cart:
<% 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 have examples that demonstrate the conditional and iterator tags.
Conditional Tags
The
iftag allows the conditional execution of its body according to the value of thetestattribute. The following example frombookcatalog.jsptests whether the request parameterAddis empty. If the test evaluates totrue, the page queries the database for the book record identified by the request parameter and adds the book to the shopping cart:<c:if test="${!empty param.Add}"> <c:set var="bid" value="${param.Add}"/> <jsp:useBean id="bid" 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 id="bookRow" type="java.util.Map" /> <jsp:useBean id="addedBook" class="database.Book" scope="page" /> ... <% cart.add(bid, addedBook); %> ... </c:if>The
choosetag performs conditional block execution by the embeddedwhensubtags. It renders the body of the firstwhentag whose test condition evaluates totrue. If none of the test conditions of nestedwhentags evaluates totrue, then the body of anotherwisetag is evaluated, if present.For example, the following sample code shows how to render text based on a 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>The
choose,when, andotherwisetags can be used to construct anif-then-elsestatement 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 Tags
The
forEachtag allows you to iterate over a collection of objects. You specify the collection via theitemsattribute, and the current item is available through a variable named by thevarattribute.A large number of collection types are supported by
forEach, including all implementations ofjava.util.Collectionandjava.util.Map. If theitemsattribute is of typejava.util.Map, then the current item will be of typejava.util.Map.Entry, which has the following 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 for the iteration is automatically wrapped with its standard wrapper class (for example,Integerforint,Floatforfloat, and so on).Implementations of
java.util.Iteratorandjava.util.Enumerationare supported, but they must be used with caution.IteratorandEnumerationobjects are not resettable, so they should not be used within more than one iteration tag. Finally,java.lang.Stringobjects can be iterated 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 the
forEachtag:<c:forEach var="item" items="${sessionScope.cart.items}"> ... <tr> <td align="right" bgcolor="#ffffff"> ${item.quantity} </td> ... </c:forEach>The
forTokenstag is used to iterate over a collection of tokens separated by a delimiter.Similarly to the value attribute of the
c:settag (see Variable Support Tags), theitemsattribute offorEachandforTokenscan also take a deferred value expression so that JavaServer Faces tags can be included within these tags.As described in Variable Support Tags, JavaServer Faces technology (see Chapter 9) supports a multi-phase life cycle. Therefore, any JavaServer Faces component tags that are included in the
forEachtag or theforTokenstag must have access to the variable referenced by theitemsattribute at different phases of the life cycle, not just during the rendering phase. Consider the following code:<c:forEach var="book" items="#{BooksBean.books}"> ... <h:inputText id="quantity" value="#{book.quantity}"/> ... </c:forEach>The
itemsattribute uses a deferred value expression, which means that thebookvariable it references is available not only during the rendering phase of the JavaServer Faces life cycle but also during the later stages of the life cycle. Therefore, whatever values the user enters into thequantitycomponent tags are updated to the external data object during the appropriate stage of the life cycle.If the expression referenced by the
itemsattribute used immediate evaluation syntax then thebookvariable would be available only when the component is rendered during the render response phase. This would prevent the values the user enters into the components from being converted, validated, or updated to the external data object during the later phases of the life cycle. The JavaServer Faces version of Duke's Bookstore includes aforEachtag on itsbookcatalog.jsppage.URL Tags
The
jsp:includeelement provides for the inclusion of static and dynamic resources in the same context as the current page. However,jsp:includecannot access resources that reside outside the web application, and it causes unnecessary buffering when the resource included is used by another element.In the following example, the
transformelement uses the content of the included resource as the input of its transformation. Thejsp:includeelement reads the content of the response and writes it to the body content of the enclosing transform element, which then rereads exactly the same content. It would be more efficient if thetransformelement could access the input source directly and thereby avoid the buffering involved in the body content of the transform tag.The
importtag is therefore the simple, generic way to access URL-based resources, whose content can then be included and or processed within the JSP page. For example, in XML Tag Library,importis used to read in the XML document containing book information and assign the content to the scoped variablexml:The
paramtag, analogous to thejsp:paramtag (see jsp:param Element, page 141), can be used withimportto specify request parameters.In Session Tracking (page 88) we discuss how an application must rewrite URLs to enable session tracking whenever the client turns off cookies. You can use the
urltag to rewrite URLs returned from a JSP page. The tag includes the session ID in the URL only if cookies are disabled; otherwise, it returns the URL unchanged. Note that this feature requires that the URL be relative. Theurltag takesparamsubtags to include parameters in the returned URL. For example,bookcatalog.jsprewrites the URL used to add a book to the shopping cart as follows:<c:url var="url" value="/catalog" > <c:param name="Add" value="${bookId}" /> </c:url> <p><strong><a href="${url}">
The redirecttag sends an HTTP redirect to the client. Theredirecttag takesparamsubtags for including parameters in the returned URL.Miscellaneous Tags
The
catchtag provides a complement to the JSP error page mechanism. It allows page authors to recover gracefully from error conditions that they can control. Actions that are of central importance to a page should not be encapsulated in acatch; in this way their exceptions will propagate instead to an error page. Actions with secondary importance to the page should be wrapped in acatchso that they never cause the error page mechanism to be invoked.The exception thrown is stored in the variable identified by
var, which always has page scope. If no exception occurred, the scoped variable identified byvaris removed if it existed. Ifvaris missing, the exception is simply caught and not saved.The
outtag evaluates an expression and outputs the result of the evaluation to the currentJspWriterobject. The syntax and attributes are as follows:If the result of the evaluation is a
java.io.Readerobject, then data is first read from theReaderobject and then written into the currentJspWriterobject. The special processing associated withReaderobjects improves performance when a large amount of data must be read and then written to the response.If
escapeXmlis true, the character conversions listed in Table 6-3 are applied.
Table 6-3 Character Conversions Character Character Entity Code<<>>&& ''""