The Java EE 5 Tutorial

Simple and Fragment Attribute and Variable Example

The Duke’s Bookstore catalog tag, defined in tut-install/javaeetutorial5/examples/web/bookstore3/web/WEB-INF/tags/catalog.tag, is a custom tag with simple and fragment attributes and variables. The tag renders the catalog of a book database as an HTML table. The tag file declares that it sets variables named price and salePrice using variable directives. The fragment normalPrice uses the variable price, and the fragment onSale uses the variables price and salePrice. Before the tag invokes the fragment attributes using the jsp:invoke element, the web container passes values for the variables back to the calling page.

<%@ attribute name="bookDB" required="true"
    type="database.BookDB" %>
<%@ attribute name="color" required="true" %>
<%@ attribute name="normalPrice" fragment="true" %>
<%@ attribute name="onSale" fragment="true" %>

<%@ variable name-given="price" %>
 <%@ variable name-given="salePrice" %>

<c:forEach var="book" begin="0" items="${bookDB.books}">
    <c:set var="bookId" value="${book.bookId}" />
    <td bgcolor="${color}">
         <c:url var="url" value="/bookdetails" >
            <c:param name="bookId" value="${bookId}" />
        <a href="${url}"><
     <td bgcolor="${color}" rowspan=2>
    <c:set var="salePrice" value="${book.price * .85}" />
    <c:set var="price" value="${book.price}" />
        <c:when test="${book.onSale}" >
            <jsp:invoke fragment="onSale" />
            <jsp:invoke fragment="normalPrice"/>



The page bookcatalog.jsp invokes the catalog tag that has the simple attributes bookDB, which contains catalog data, and color, which customizes the coloring of the table rows. The formatting of the book price is determined by two fragment attributes, normalPrice and onSale, that are conditionally invoked by the tag according to data retrieved from the book database.

<sc:catalog bookDB ="${bookDB}" color="#cccccc">
    <jsp:attribute name="normalPrice">
        <fmt:formatNumber value="${price}" type="currency"/>
    <jsp:attribute name="onSale">
        <fmt:formatNumber value="${price}" type="currency"/>
        <font color="red">
        <fmt:formatNumber value="${salePrice}" type="currency"/>

The screen produced by tut-install/javaeetutorial5/examples/web/bookstore3/web/bookcatalog.jsp is shown in Figure 8–2. You can compare it to the version in Figure 5–2.

Figure 8–2 Book Catalog

Screen capture of Duke's Bookstore book catalog, with
titles, authors, prices, and "Add to Cart" links. Three discount prices are