Mega Code Archive

 
Categories / Java / JSP
 

Create your own tag

///    <!-- this must be added to the web application's web.xml --> <taglib>   <taglib-uri>/rntsoft</taglib-uri>   <taglib-location>/WEB-INF/rntsoft.tld</taglib-location> </taglib> // create File:rntsoft.tld in the /WEB-INF/ <!DOCTYPE taglib   PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"    "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">     <!-- a tab library descriptor --> <taglib xmlns="http://java.sun.com/JSP/TagLibraryDescriptor">   <tlib-version>1.0</tlib-version>   <jsp-version>1.2</jsp-version>   <short-name>rntsoft Simple Tags</short-name>   <!-- this tag manipulates its body content by converting it to upper case     -->   <tag>     <name>bodyContentTag</name>     <tag-class>com.rntsoft.BodyContentTag</tag-class>     <body-content>JSP</body-content>     <attribute>       <name>howMany</name>     </attribute>   </tag> </taglib> //compile the following code into WEB-INF\classes\com\rntsoft package com.rntsoft; import java.io.IOException; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.tagext.BodyContent; import javax.servlet.jsp.tagext.BodyTagSupport; public class BodyContentTag extends BodyTagSupport {   private int iterations, howMany;   public void setHowMany(int i)   {     this.howMany = i;   }   public void setBodyContent(BodyContent bc)   {     super.setBodyContent(bc);     System.out.println("BodyContent = '" + bc.getString() + "'");   }      public int doAfterBody()   {     try      {           BodyContent bodyContent = super.getBodyContent();       String      bodyString  = bodyContent.getString();       JspWriter   out         = bodyContent.getEnclosingWriter();       if ( iterations % 2 == 0 )          out.print(bodyString.toLowerCase());       else         out.print(bodyString.toUpperCase());       iterations++;       bodyContent.clear(); // empty buffer for next evaluation     }     catch (IOException e)      {       System.out.println("Error in BodyContentTag.doAfterBody()" + e.getMessage());       e.printStackTrace();     } // end of catch     int retValue = SKIP_BODY;          if ( iterations < howMany )        retValue = EVAL_BODY_AGAIN;          return retValue;   } } // start comcat and load the bodyContent.jsp in browser <%@ taglib uri="/rntsoft" prefix="rntsoft" %> <html>   <head>     <title>A custom tag: body content</title>   </head>   <body>     This page uses a custom tag manipulates its body content.     Here is its output:     <ol>       <rntsoft:bodyContentTag howMany="3">         <li>rntsoft.com</li>       </rntsoft:bodyContentTag>     </ol>   </body> </html>