For
creating any custom tag, we need to follow following steps:
ü Create
the Tag handler class and perform action at the start or at the end
of the tag.
ü Create
the Tag Library Descriptor (TLD) file and
define tags
ü Create the JSP file that uses the Custom tag defined in the TLD file
Example to understand the custom tag
Create
the Tag handler class
- To
create the Tag Handler, we are inheriting the TagSupport class and
overriding its method doStartTag().To
write data for the jsp, we need to use the JspWriter
class.
- The PageContext class provides getOut() method that returns the instance of JspWriter class.
TagSupport class provides instance of pageContext bydefault.
File:
DashzinTagHandler.java
package com.dashzin.jsp;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
import org.apache.jasper.el.JspELException;
public class DashzinTagHandler extends TagSupport{
public int doStartTag() throws JspELException{
JspWriter out=pageContext.getOut();
try{
out.print("welcome
to custome tag");
}catch(Exception e){
e.printStackTrace();
}
return SKIP_BODY; //will not evaluate the body content of the tag ;
}
}
Create
the TLD file
Tag Library Descriptor (TLD)
file contains information of tag and Tag Hander classes. It must be contained
inside the WEB-INFdirectory.
File: Dashzintags.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/j2ee/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>simple</short-name>
<uri>http://tomcat.apache.org/example-taglib</uri>
<tag>
<name>cus</name>
<tag-class>com.dashzin.jsp.DashzinTagHandler</tag-class>
</tag>
</taglib>
Create
the JSP file
- Let's
use the tag in our jsp file. Here, we are specifying the path of tld file
directly. But it is recommended to use the uri name instead of full path of tld
file. We will learn about uri later.
- It
uses taglib directive to use the tags defined in the tld file.
File: index.jsp
<%@ taglib uri="WEB-INF/Dashzintags.tld"
prefix="m" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD
HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=ISO-8859-1">
<title>Check custome tag in jsp</title>
</head>
<body>
Try to print welcome massage: <m:cus/>
</body>
</html>
Output:-
Try to print welcome massage: welcome to custome tag
0 comments:
Post a Comment