Custom Tag Full Example
hello friends.i am posting a very simple example of how to make custom Tag using servlet -jsp code.this is fun..what is required is given below:
(1) you need to define servlet that extends TagSupport class
(2)define .tld file into web-inf.where all configuration related to tag library is placed.
(3) Referance the tag library configuration file into jsp as given below:
<%@taglib uri="/WEB-INF/demo.tld" prefix="sample" %>
sample Servlet code :
package org.demo.customtag;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
//tag handler
public class Hello extends TagSupport
{
/**
*
*/
private static final long serialVersionUID = 1L;
private String name=null;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
//CALLED BY JSP CONTAINER WHEN IT ENCOUNTER STARTING CUSTOM TAG
public int doStartTag()
{
try
{
JspWriter out=pageContext.getOut();
out.println("<table border='1'>");
if(name!=null)
out.println("<tr><td> Hello"+name+"</td></tr>");
else
out.println("<tr><td> Hello world </td></tr>");
}
catch(Exception e)
{
throw new Error("All is not well dude");
}
return SKIP_BODY;
}
//CALLED BY JSP CONTAINER WHEN IT ENCOUNTER CLOSING CUSTOM TAG
public int doEndTag()
{
try
{
JspWriter out = pageContext.getOut();
out.println("</table>");
}
catch(Exception e)
{
throw new Error("All not well dude");
}
return EVAL_PAGE;
}
}
there are two enumerations SKIP_BODY & EVAL_PAGE is used in code :
first enumeration will be used to skip the body straight away after start custom tag is encountered.jsp container will not execute doStartTag() after it finds starting of custom tag.
EVAL_PAGE if defined in methdod than rest of the jsp code which is defined will continue to execute.
demo
Demo.xml file under WEB-INF
<?xml version="1.0" encoding="UTF-8"?>
<taglib>
<tlibversion>1.0</tlibversion>
<jspversion>1.1</jspversion>
<shortname>hello</shortname>
<info>Sample taglib for Substr operation</info>
<uri>http://nisargpathakblogspot.com</uri>
<tag>
<name>substring</name>
<tagclass>org.demo.customtag.Hello</tagclass>
<info>Helloworld Function</info>
<attribute>
<name>name</name>
<required>true</required>
</attribute>
</tag>
</taglib>
Hello.html
<%@taglib uri="/WEB-INF/demo.tld" prefix="sample" %>
<html>
<head>
<title>Custom Tag Demo </title>
</head>
<body bgcolor="#ffffff">
<hr />
<sample:substring name="Akansha Dave"></sample:substring>
<hr />
</body>
</html>
hope you got it ..
for any query ping me on pathak.nisarg@yahoo.com
No comments:
Post a Comment