background image

Simple Attribute Example

<< Custom Tag Examples | Two Fragment Attributes >>
<< Custom Tag Examples | Two Fragment Attributes >>

Simple Attribute Example

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" %>
<center>
<table>
<c:forEach var=
"book" begin="0" items="${bookDB.books}">
<tr>
<c:set var=
"bookId" value="${book.bookId}" />
<td bgcolor=
"${color}">
<c:url var=
"url" value="/bookdetails" >
<c:param name=
"bookId" value="${bookId}" />
</c:url>
<a href=
"${url}"><
strong>${book.title}&nbsp;</strong></a></td>
<td bgcolor=
"${color}" rowspan=2>
<c:set var=
"salePrice" value="${book.price * .85}" />
<c:set var=
"price" value="${book.price}" />
<c:choose>
<c:when test=
"${book.onSale}" >
<jsp:invoke fragment=
"onSale" />
</c:when>
<c:otherwise>
<jsp:invoke fragment=
"normalPrice"/>
</c:otherwise>
</c:choose>
&nbsp;</td>
...
</table>
</center>
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
Encapsulating Reusable Content Using Tag Files
The Java EE 5 Tutorial · September 2007
244