Recipe 22.8 Creating a Simple Tag Handler


You want to create a JSP 2.0 simple tag handler.


Create a Java class that either implements the SimpleTag interface or extends the SimpleTagSupport class.


In an effort to simplify custom tag development, the JSP 2.0 specification added the javax.servlet.jsp. tagext .SimpleTag interface and the SimpleTagSupport class. The SimpleTagSupport class is designed to be the base class for tag handlers that implement SimpleTag . These tag handlers have to implement just one method, doTag( ) .

The JSP 2.0 specification states that vendors should not cache simple tag handlers, so developers do not have to worry about the reuse of tag handler objects and releasing object state in their code.

Example 22-6 mimics the logo tag handler created in earlier recipes, but uses the SimpleTagSupport class from the JSP 2.0 API instead.

Example 22-6. A simple tag handler displaying a logo
 package com.jspservletcookbook;     import; import javax.servlet.*; import javax.servlet.http.*;  import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*;  /** This tag generates a thumbnail image using an HTML img tag, aligned next to a text  message. The user specifies the content of the message and the Heading level (i.e., <H1>- <H6>) */  public class SimpleLogoTag extends SimpleTagSupport{  private String heading = null;     private String image =null;     private String width =null;     private String height =null;  public void doTag( ) throws JspException, IOException{          //JspContext provides access to the JspWriter for generating       //text from the tag. You can also get any stored attribute values       //using JspContext       JspContext jspContext = getJspContext( );          //this method assumes that attribute properties have been set.       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( )); }            //Get a JspWriter to produce the tag's output       JspWriter out = jspContext.getOut( );            //the value of the 'imgDir' attribute is the web app's /images        //directory; the directory path is stored in a session attribute       String imgDir = (String) jspContext.findAttribute("imgDir");            if (imgDir == null  "".equals(imgDir))           throw new JspException(            "No attribute provided specifying the application's " +            "image directory.");            //display the img and H HTML tags       out.println(new StringBuffer("<img src=\"").append(imgDir).        append(image).append("\" width=\"").append(width).        append("\" height=\"").append(height).append("\" align=\"left\">").        append("<H").append(heading).append(">").toString( ));              // getJspBody( ) returns a 'JspFragment' object; calling 'invoke( )'       //on this object with a 'null' parameter will use the JSP page's        //JspWriter to output the tag's nested content in the JSP       getJspBody( ).invoke(null);       out.println(new StringBuffer("</H").append(heading).        append(">").toString( ));      }//doTag  //Attribute-related setter methods   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;   }  }// SimpleLogoTag  

This simple tag handler accesses a JspContext object by calling the SimpleTagSupport's getJspContext( ) method. The code uses the JspContext to obtain the value of an attribute stored in the session, as well as to access a JspWriter to generate the tag's output:

 JspContext jspContext = getJspContext( ); //further along in the code... JspWriter out = jspContext.getOut( );      //the value of the 'imgDir' attribute is the web app's images  //directory; it is stored in a session attribute String imgDir = (String) jspContext.findAttribute("imgDir"); //code continues... 

Calling the SimpleTagSupport's getJspBody( ) method returns a JspFragment object, which represents a chunk of JSP code as an object. Calling this object's invoke( ) method with null as the parameter directs the output of the fragment to the JspWriter available to the tag handler:

 //Get the tag's body content and output it using the JspWriter //that is available by calling JspContext.getOut( ) getJspBody( ).invoke(null); 

This code displays the content or text that the JSP developer included within the custom action's start and end tags. The tag handler uses the tag's body content as the textual logo message. Figure 22-1 in Recipe 22.1 shows what the JSP page looks like in a web browser.

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 a tag library 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.9 on creating a TLD for 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: