Custom Tags in JSP 2.0

The JSP pages in Examples Example 20-10 and Example 20-11 use the custom tags <tags:attention> and <tags:box>. In both cases, the JSP files include an @taglib directive that maps the tags: prefix to a directory in the WEB-INF/ directory of the web application. Within that directory are files named attention.tag and box.tag, which provide expansions for the two tags. Note that the tag names are defined by the filenames of the .tag files.

The <attention> tag is a trivial one; its very short body is the subject of Example 20-12. It consists simply of a <span> tag and some CSS style attributes that are wrapped around the contents to which the user’s attention should be drawn. In the tag body, the <jsp:doBody/> tag is a placeholder for the contents of the <attention> tag.

Example 20-12. attention.tag

<span style="color:#f00; font-weight: bold;">
<jsp:doBody/>
</span>

The box.tag file of Example 20-13 is somewhat more complex because it can accept attributes. The @attribute directives at the top of the file declare these attributes. The bulk of the file consists of HTML <div> tags and CSS styles for the box with optional color, border, margins, and title. Expressions in ${ } place the attribute values into the CSS style attributes as needed. Note that the expressions use the ?: ternary operator to provide default values when the attribute is undefined. Again, the <jsp:doBody/> tag is used as a placeholder for the contents of the box.

Note that the custom tags shown ...

Get Java Examples in a Nutshell, 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.