The Java EE 5 Tutorial

Fragment Attributes

A JSP fragment is a portion of JSP code passed to a tag handler that can be invoked as many times as needed. You can think of a fragment as a template that is used by a tag handler to produce customized content. Thus, unlike a simple attribute which is evaluated by the container, a fragment attribute is evaluated by a tag handler during tag invocation.

To declare a fragment attribute, you use the fragment attribute of the attribute directive (see Declaring Tag Attributes in Tag Files) or use the fragment subelement of the attribute TLD element (see Declaring Tag Attributes for Tag Handlers). 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, and Declaring Tag Variables for Tag Handlers).

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.