Saturday, 14 September 2013

Custom Tag [with body]



1.   Create a handler file  like :  myTag.java

 package mypac;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
// writer:  @author ashy
public class myTag extends BodyTagSupport {
      /** Creates a new instance of myTag */
    public myTag() { }
     String color;
        public void setColor(String color)
        {
        this.color=color;
        }
    public int doStartTag()throws JspException
    {    try
        {
        JspWriter jw=pageContext.getOut();
     jw.println("<table bgcolor='"+color+"'");
     jw.println("><tr><td>");
      
        }
     catch(Exception e)
     {         }
return EVAL_BODY_INCLUDE;
    }
    public int doEndTag()
    {
        try{
              JspWriter jw=pageContext.getOut();
      jw.println("</td><tr/></table>");
        }
catch(Exception e)
        {    }
        return EVAL_PAGE;
    }      
}
2.  Create a tag handler under tlds folder under WEB-INF folder like:bodyTagLib.tld
Code:
<?xml version="1.0" encoding="UTF-8"?>
<taglib version="2.0" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee web-jsptaglibrary_2_0.xsd">
  <tlib-version>1.0</tlib-version>
  <short-name>bodytaglib</short-name>
  <uri>/WEB-INF/tlds/bodyTagLib</uri>
    <tag>
              <name>ashwani</name>
       <tag-class>mypac.myTag</tag-class>
       <body-content>jsp</body-content>
       <attribute>
           <name>color</name>
           <required>true</required>
           <rtexprvalue>true</rtexprvalue>
                  </attribute>
   </tag>
</taglib>
3.  Final step is to implement this tag like:
Code:
<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<%@taglib uri="/WEB-INF/tlds/bodyTagLib.tld" prefix="m"%>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
    <h1>JSP Page</h1>
   
 <m:ashwani color="red">
     ashwani
     </m:ashwani>
        </body>
</html>