[ Team LiB ] Previous Section Next Section

20.12 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;">

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 here are a JSP 2.0 feature. Prior to JSP 2.0, custom tags had to be defined as Java classes and configured with a TLD (tag library descriptor) file. While this can be useful for tags with advanced features, many useful custom tags are simple templates like these, and JSP 2.0 makes them much easier to define.

Example 20-13. box.tag
<%@ attribute name="bgcolor" %>
<%@ attribute name="border" %>
<%@ attribute name="padding" %>
<%@ attribute name="margin" %>
<%@ attribute name="title" %>
<div style="
   background-color: ${bgcolor!=null?bgcolor:"transparent"};
   border: solid black ${border!=null?border:"0"}px;
   margin: ${margin!=null?margin:"5"}px;
<div style="
   background-color: #000;
   color: ${bgcolor!=null?bgcolor:"transparent"};
   margin: 0;
   padding: ${title!=null?4:0}px;
   font-family: sans-serif;
   font-weight: bold;
   text-align: left;
<div style="padding: ${padding!=null?padding:"5"}px;">
    [ Team LiB ] Previous Section Next Section