JSP Custom tags Example


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.

A Simple Custom tags Example:

1.Create a Java Program

2.import javax.servlet.jsp.*,javax.servlet.jsp.tagext.* packages

3.Extends the TagSupport Class

4.Java Program Contain two Default Methods.
a)doStartTag
b)doEndTag

doStartTag:
1.The doStartTag method is invoked when the start tag is encountered
2.This method returns SKIP_BODY because a simple tag has no body

doEndTag:
1.The doEndTag method is invoked when the end tag is encountered
2.This method returns SKIP_BODY because a simple tag has no body

TagClass.java

import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;

public class TagClass extends TagSupport{

private String data=null;

public void setData(String value){
data= value;
}

public String getData(){
return(data);
}

public int doStartTag()throws JspException{
try{
JspWriter out=pageContext.getOut();
out.println(name);

}catch(Exception e){}
return SKIP_BODY;
}

public int doEndTag(){
return SKIP_BODY;
}

}

5.The Java Program Contain one Variable data(which has Getter and Setter Methods)

6.Create tld File.

7.We have to Create attribute For the Variable data

8.Syntax For Creating attribute:

<taglib>

<tag>

<attribute>
<name>data</name>//Name Can be Same as we can given within the tags
<required>true</required>//Requried Field Show Whether it is Mandatory or Not
</attribute>

<attribute>
<name>id</name>
<required>false</required>
</attribute>

</tag>

</taglib>

taglib.tld

<?xml version=”1.0″ encoding=”ISO-8859-1″ ?>
<!DOCTYPE taglib PUBLIC “-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN” “http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd”>

<taglib>

<tlib-version>1.0</tlib-version>

<jsp-version>1.2</jsp-version>

<short-name>form</short-name>

<tag>

<name>Show</name>
<tag-class>com.TagClass</tag-class>
<body-content>JSP</body-content>
<description>Simple Customs tags Example</description>

<attribute>
<name>data</name>
<required>true</required>
</attribute>

</tag>

</taglib>

9.Create a JSP Page.

10.Include this tag at the begining of the JSP Page

<%@ taglib uri=”/WEB-INF/tld/taglib.tld” prefix=”custom” %>

11.Create this Tag at the JSP Page

<custom:Show data=”Custom Tag Example”></custom:Show>

12.Output:

Custom Tag Example

Popularity: 7% [?]

You can leave a response, or trackback from your own site.

Leave a Reply

Designed by: Business Web Hosting | Thanks to Buy Icons, travel tips and Used Cars