background image

Dynamic Attributes

<< Types of Tags | Deferred Value and Method >>
<< Types of Tags | Deferred Value and Method >>

Dynamic Attributes

To declare a fragment attribute, you use the fragment attribute of the attribute directive (see
"Declaring Tag Attributes in Tag Files" on page 237
) or use the fragment subelement of the
attribute
TLD element (see
"Declaring Tag Attributes for Tag Handlers" on page 252
). You
define the value of a fragment attribute by using a jsp:attribute element. When used to
specify a fragment attribute, the body of the jsp:attribute element can contain only static text
and standard and custom tags; it cannot contain scripting elements (see
Chapter 9, "Scripting in
JSP Pages"
).
JSP fragments can be parameterized by means of expression language (EL) variables in the JSP
code that composes the fragment. The EL variables are set by the tag handler, thus allowing the
handler to customize the fragment each time it is invoked (see
"Declaring Tag Variables in Tag
Files" on page 238
, and
"Declaring Tag Variables for Tag Handlers" on page 254
).
The catalog tag discussed earlier accepts two fragments: normalPrice, which is displayed for a
product that's full price, and onSale, which is displayed for a product that's on sale.
<sc:catalog bookDB =
"${bookDB}" color="#cccccc">
<jsp:attribute name=
"normalPrice">
<fmt:formatNumber value=
"${price}" type="currency"/>
</jsp:attribute>
<jsp:attribute name=
"onSale">
<strike><fmt:formatNumber value=
"${price}"
type=
"currency"/></strike><br/>
<font color=
"red"><fmt:formatNumber value="${salePrice}"
type=
"currency"/></font>
</jsp:attribute>
</sc:catalog>
The tag executes the normalPrice fragment, using the values for the price EL variable, if the
product is full price. If the product is on sale, the tag executes the onSale fragment using the
price
and salePrice variables.
Dynamic Attributes
A dynamic attribute is an attribute that is not specified in the definition of the tag. Dynamic
attributes are used primarily by tags whose attributes are treated in a uniform manner but
whose names are not necessarily known at development time.
For example, this tag accepts an arbitrary number of attributes whose values are colors and
outputs a bulleted list of the attributes colored according to the values:
<colored:colored color1=
"red" color2="yellow" color3="blue"/>
You can also set the value of dynamic attributes using an EL expression or using the
jsp:attribute
element.
Types of Tags
The Java EE 5 Tutorial · September 2007
230