Processing Fragment Attributes

In all the examples so far, the custom action attribute types have been either regular Java classes or primitive types. The container evaluates attributes like these once and passes the resulting value to the tag handler through the attribute setter methods; however, it’s perfectly legal to declare an attribute of type JspFragment. In this case, the container does not evaluate the value. Instead it passes a fragment representation of the value to the setter method that the tag handler can evaluate as many times as needed, in exactly the same manner as the body fragment.

Fragment attributes make a lot of sense for a custom action where the page author should be able to specify dynamic templates, or patterns, that are applied to elements of a collection. One example is a custom action that iterates over the days in a month. The page author should be able to describe different templates for rendering weekdays than for weekends, for instance. Let’s develop a tag handler for a custom action that does just that and more. Here’s how the custom action can be used in a JSP page:

<table border="1" cellspacing="0">
  <caption>
    <fmt:formatDate value="${now}" pattern="MMMM yyyy" />
  </caption>
  <ora:calendar date="${now}" var="c">
                  <jsp:attribute name="beforePattern">
      <tr>
    </jsp:attribute>
                  <jsp:attribute name="afterPattern">
      </tr>
    </jsp:attribute>
                  <jsp:attribute name="dayNamePattern">
      <th><fmt:formatDate value="${c}" pattern="EE" /></th>
    </jsp:attribute>
                  <jsp:attribute ...

Get JavaServer Pages, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.