Recipe 22.1 Creating a Classic Tag Handler


You want to create a classic JSP 1.2-style tag handler for a custom action.


Create a Java class that extends one of the Tag support classes in the javax.servlet.jsp. tagext package, such as BodyTagSupport .


There are numerous types of custom tags you can create for JSPs, such as actions that ignore their bodies (empty tags), actions that are nested within other custom actions, and custom tags that use their body content. In fact, entire books have been dedicated solely to JSP custom tag development! Instead of being exhaustive in this book, I show how to create a fairly simple classic tag that adds an image logo to a JSP page with a text message. You can then infer details for your own programming tasks from this example.

The sample tag is designed to allow a page designer to specify an logo's image, its width and height, and a text message to sit alongside the image.

Example 22-1 shows the classic tag handler for this custom action. This Java class extends BodyTagSupport , since it uses the tag's nested content for the logo's text message.

Example 22-1. A classic tag handler for inserting an image and markup
 package com.jspservletcookbook;     import javax.servlet.*; import javax.servlet.http.*;  import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; /** This tag generates a thumbnail image using the HTML img tag, next to  a text message.  The user specifies the content of the message and the Heading level (i.e., <H1>-<H6>) */ public class LogoTag extends BodyTagSupport {     //These variable represent the custom tag's attributes     private String heading = null;     private String image =null;     private String width =null;     private String height =null;   //this method assumes that attribute properties have been set.   public int doStartTag( ) throws JspException{            try {              int h = new Integer(heading).intValue( );              if(! (h > 0 && h < 7))         throw new JspException(         "The 'heading' attribute value must between 1 and 6 inclusive.");              } catch (Exception e) { throw new JspException(e.getMessage( )); }        return EVAL_BODY_BUFFERED;      }   public int doEndTag( ) throws JspException {     JspWriter out = pageContext.getOut( );          //the 'images' directory is located in the web app's     //root directory     String imgDir = ((HttpServletRequest) pageContext.     getRequest( )).getContextPath( ) + "/images/";     //get the text provided between the custom action's     // start and end tags     String message = getBodyContent( ).getString( ).trim( );     try{        //build the HTML img tag        out.println("<img src=\""+ imgDir + image + "\" width=\"" + width +        "\" height=\"" + height + "\" align=\"left\">" + "<H" + heading + ">" +        message + "</H" + heading+ ">");          } catch ( io) {}         return EVAL_PAGE;   } //doEndTag       //methods designed to set attribute values  public void setHeading(String level){     this.heading= level;   }      public void setImage(String name){     this.image = name;   }      public void setWidth(String width){     this.width = width;   }      public void setHeight(String height){     this.height = height;   }   //the JSP container may cache and reuse tag handler objects.   //this method releases instance variables so that the tag handler   //can be reused afresh   public void release( ){             heading = null;      image =null;      width =null;      height =null;        }// release  } 

Classic tag handlers are like JavaBeans. You declare the custom tag's attributes as instance variables, or properties , and define setter methods for each attribute. If you just want to manipulate the custom tag's body, define the doEndTag( ) method. When the JSP container invokes doEndTag( ) , developers can use this method to evaluate the body content that the tag user has placed between the action's start and end tags. Example 22-1 also defines the doStartTag( ) method to check that the tag user has included a valid value for the header attribute (a number between one and six, inclusive, for this example code).

When the doStartTag( ) method is invoked, any attribute values that the user has set are available, but the tag's body content is not.

The doEndTag( ) method uses the various tag attribute values to build an img and H tag that results in the display of a simple logo in the JSP page where the tag is used. Here's an example of how a JSP would use the action defined by this tag handler:

 <%-- import the tag library with 'taglib' directive --%>  <%@ taglib uri="" prefix="cbck" %>  <%-- JSP page continues... --%> <%-- Use the 'logo' tag --%>  <cbck:logo heading="1" image="stamp.gif" width="42" height="54">Thanks for visiting</ cbck:logo>  

Figure 22-1 shows a JSP that uses the tag defined by Example 22-1.

Figure 22-1. A JSP page uses a custom tag that displays an image and a heading

The JSP using this tag outputs HTML that looks like this:

 <img src="/home/images/stamp.gif" width="42" height="54" align="left">   <H1> Thanks for visiting</H1> 

You might respond by exclaiming, "The designer can just enter these HTML tags manually, and they don't have to deal with the custom tag's syntax!" This is absolutely true; however, the tag takes care of the default location for the images directory, positions and aligns the image, and checks whether the attribute level is correct. In other words, it performs a lot of routine work and removes the possibility of silly typographical mistakes.

Also consider that this is a simple example; what if the image was a Flash file instead? A custom tag could take care of all of the complex details for embedding the Flash in the HTML page and generating proprietary attribute values, leaving the graphical positioning of the media file up to the tag user.

A nice rule of thumb with custom tags is this: leave automated, complex, or tedious work to the tag handler, and reserve configurable details for the tag's attributes.

See Also

The JSP 2.0 specification web page:; Recipe 22.2 and Recipe 22.3 on creating TLD files for tag libraries; Recipe 22.4 and Recipe 22.5 on packaging tag libraries in a web application; Recipe 22.6 on using the custom tag in a JSP; Recipe 22.7 on handling exceptions in tags; Recipe 22.8 and Recipe 22.9 on creating a simple tag handler; Recipe 22.10 on using the simple tag handler in a JSP; Recipe 22.11-Recipe 22.14 on using a JSP tag file; Recipe 22.15 on adding a listener class to a tag library; the custom-tag sections of Hans Bergsten's JavaServer Pages , Third Edition (O'Reilly).

Java Servlet & JSP Cookbook
Java Servlet & JSP Cookbook
ISBN: 0596005725
EAN: 2147483647
Year: 2004
Pages: 326

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: