Tag Handler in JSP

The custom tag library is a powerful feature of JSP that is used to separate the front end presentation from the middle and backend presentation.

Tag Handler in JSP

Tag Handler in JSP

        

What is a custom tag: The custom tag library is a powerful feature of JSP that is used to separate the front end presentation from the middle and backend presentation. Custom tags are usually distributed in the form of a tag library, which defines a set of related custom tags and contains the objects that implement the tags. Custom tag libraries allow the java programmer to write code that provides data access and other services, and they make those features available to the jsp author in a simple to use XML- like fashion. 

Tag Library: There are two types of components for a tag library, the tag library descriptor file and the tag handlers. With the help of this a JSP is able to use tags contained in the library within its page.

The TLD file: TLD means tag library descriptor. It is a XML file that describes the library. The tld contains the information about the library and the tags contained in the library. Some attributes of the tld files are given below:

<taglib>: It is the tag library.

<tlibversion>: It tells the tag library's version.

<jspversion>: It tells about the jsp version.

<shortname>: This short name is used as a prefix value in taglib directives.

<uri>: By this we can uniquely identifies the tag library.

<info>: If we have to give some information about the tag library.

Tag Handler: We have to define the tag in a handler class. TagSupport is the base class used for simple tags. This class can be found in the javax.servlet.jsp.tagext package.

The output of the program is given below:

//TagHandlerForm.jsp
<%@ taglib uri="/roseindia.tld" prefix="roseindia" %>
<html>
        <head>
                <title>Your Standard Hello World Demo</title>
        </head>
        <body bgcolor="#ffffff">
               
                <roseindia:hello name="Roseindia.net"/><br>
               //when the name is null then, it will display hello world
				<roseindia:hello /> 
        </body>
</html>
//roseindia.tld
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN"
"HTTP://JAVA.SUN.COM/J2EE/DTDS/WEB-JSPTAGLIBRARY_1_1.DTD">
<taglib>
	<tlibversion>1.0</tlibversion>
	<jspversion>1.1</jspversion>
	<shortname>roseindia</shortname>
	<info>roseindia Sample Tag library</info>
  <!--A Simple tag -->
  <tag>
    <name>hello</name>
    <tagclass>TLD.Hello </tagclass>
  <!--Body content can have a value of 
  	 empty: no body 
      JSP: body that is evaluated by container, then possibly processed by the tag 
      tagdependent: body is only processed by tag; JSP in body is not evaluated.
   -->
    <bodycontent>empty</bodycontent>
    <info>
	This is a simple hello tag.
    </info>
  <!-- Optional attributes  -->
  <!-- personalized name -->
  <attribute>
      <name>name</name>
      <required>false</required>
  </attribute>
  <attribute>
      <name>iterations</name>
      <required>false</required> 
	   
    </attribute>
</tag>
</taglib>
//Hello.java
package TLD;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
public class Hello extends BodyTagSupport {
	private String name=null;
    private int iterations=1;
public void setName(String value){
    name = value;
}
	public String getName(){
          return(name);
       }
	   public void setIterations(String value){
     try {
       iterations = Integer.parseInt(value);
     } catch(NumberFormatException nfe) {
       iterations = 1;
     }	
   }
	public String getIterations(){
		return(Integer.toString(iterations));
	}
/**
* doStartTag is called by the JSP container when the tag is encountered
*/
    public int doStartTag() {
	  try {
        JspWriter out = pageContext.getOut();
        out.println("<table border=1 width=100% height=100%>");
	     if (name != null){
	      out.println("<tr><td> Hello " + name + " </td></tr>");
		 }
        else{
	      out.println("<tr><td> Hello World </td></tr>");}
	  } catch (Exception ex) {
	    throw new Error("All is not well in the world.");
	  }
	  // Must return SKIP_BODY because we are not supporting a body for this 
	  // tag.
	  return SKIP_BODY;
    }
/**
 * doEndTag is called by the JSP container when the tag is closed
 */
	public int doEndTag(){
	   try {
        	JspWriter out = pageContext.getOut();
	       out.println("</table>");
	   } catch (Exception ex){
	    	throw new Error("All is not well in the world.");
	   }
	   return EVAL_PAGE;
	}
	public int doAfterBody() throws JspTagException {
    if (iterations-- >= 1) {
      BodyContent body = getBodyContent();
      try {
		// Make sure we put anything in the output stream in the 
		// body to the output stream of the JSP
        JspWriter out = body.getEnclosingWriter();
        out.println(body.getString());
        body.clearBody(); // Clear for next evaluation
      } catch(IOException ioe) {
        throw new JspTagException("Error in Hello tag doAfterBody " + ioe);
      }
      return(EVAL_BODY_TAG);
    } else {
      return(SKIP_BODY); 
	}
}
}

The output of the program is given below:

Download this example.