Exposing Data to the Calling Page Through Variables
Attributes provide input to a custom
action, but sometimes you also need to give the page that contains
the custom action access to data produced by the custom action. For
instance, the <my:forEvenAndOdd>
action is
not all that useful unless the page can access the current iteration
value in the fragments for even and odd rows. To handle this
requirement, data can be passed from a custom action to the caller by
exposing it through declared variables.
Example 11-6 shows a version of the tag file from
Example 11-5 that’s been extended to
expose the current iteration value as a variable named
current
. All differences between the examples are
highlighted.
<%@ tag body-content="empty" %> <%@ attribute name="items" rtexprvalue="true" required="true" %> <%@ attribute name="even" fragment="true" required="true" %> <%@ attribute name="odd" fragment="true" required="true" %> <%@ variable name-given="current" variable-class="java.lang.Object" scope="NESTED" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <c:forEach items="${items}" varStatus="status" var="current"> <c:choose> <c:when test="${status.count % 2 == 0}"> <jsp:invoke fragment="even" /> </c:when> <c:otherwise> <jsp:invoke fragment="odd" /> </c:otherwise> </c:choose> </c:forEach>
The variable
directive declares the variable. The
name-given
attribute specifies its name and the
variable-class
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.