Using Undeclared Attributes
Occasionally, declaring all
attributes for a tag file can be a hassle. Say you want
to develop a tag file that generates an HTML table, and you want the
page author to be able to specify all standard attributes that an
HTML table element supports. That’s a lot of
attributes and the tag file would need to test for the existence of
each one. A better approach for this scenario is to use the
tag
directive’s
dynamic-attributes
attribute. This attribute declares
that the tag file accepts any custom action element attribute. The
attribute value is the name of a local page scope variable that holds
a collection (a Map
) with all undeclared attribute
names and values. Example 11-3 shows an example of a
tag file that uses this approach to generate a table with all request
header values.
<%@ tag body-content="empty" dynamic-attributes="dynattrs" %> <%@ attribute name="caption" required="true" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <table <c:forEach items="${dynattrs}" var="a"> ${a.key}="${a.value}" </c:forEach> > <caption>${caption}</caption> <tr> <th>Name</th> <th>Value</th> </tr> <c:forEach items="${header}" var="h"> <tr> <td>${h.key}</td> <td>${h.value}</td> </tr> </c:forEach> </table>
The dynamic-attributes
attribute declares a
variable named dynattrs
to hold the undeclared
attributes, and a JSTL <c:forEach>
action loops through the collection and adds the name and ...
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.