Step description:
1. Development label implementation class.
HelloTag_Interface.java file content:
Import javax. servlet. jsp. tagext. Tag;
Import javax. servlet. jsp. PageContext;
Import javax. servlet. jsp. JspException;
Import java. io .*;
Import javax. servlet. jsp. JspTagException;
/***//**
* Develop the Tag program by implementing the Tag Interface
*/
Public class HelloTag
Implements Tag ...{
Private PageContext pageContext;
Private Tag parent;
Public HelloTag ()...{
Super ();
}
/***//**
* Set the tab Page Context
* @ Param pageContext
*/
Public void setPageContext (PageContext pageContext )...{
This. pageContext = pageContext;
}
/***//**
* Set the upper-level label
* @ Param t
*/
Public void setParent (Tag parent )...{
This. parent = parent;
}
Public Tag getParent ()...{
Return this. parent;
}
/***//**
* Operations when the tag is started
* @ Return
* @ Throws JspException
*/
Public int doStartTag () throws JspException ...{
Return this. SKIP_BODY; // return SKIP_BODY, indicating that the label body is not calculated.
}
/***//**
* Operation when the tag is ended
* @ Return
* @ Throws JspException
*/
Public int doEndTag () throws JspException ...{
Try ...{
PageContext. getOut (). write ("Hello World! ");
}
Catch (IOException ex )...{
Throw new JspTagException ("IO Error:" ex. getMessage ());
}
Return this. EVAL_PAGE;
}
/***//**
* Release is used to Release the resources occupied by the tag program. For example, if a database connection is used, the connection should be closed.
*/
Public void release ()...{
}
}
2. Write the tag library description and create a new mytag. tld file under the WEB-INF directory:
<? Xml version = "1.0" encoding = "GBK"?>
<Taglib 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"
Version = "2.0">
<Description> A tag library exercising SimpleTag handlers. </description>
<Tlib-version> 1.0 </tlib-version>
<Short-name> my </short-name>
<Uri>/mytag </uri>
<Description> learning tag </description>
<Tag>
<Description> output Hello World </description>
<Name> hello </name>
<Tag-class> HelloTag </tag-class>
<Body-content> empty </body-content>
</Tag>
</Taglib>
3. Configure the custom tag to the project and add it to the web. xml file:
<Web-app>
...
<Taglib>
<Taglib-uri>/mytag </taglib-uri>
<Taglib-location>/WEB-INF/mytag. tld </taglib-location>
</Taglib>
...
</Web-app>
4. Use custom tags in the JSP file to compile the mytag. jsp file:
<%... @ Taglib uri = "/mytag" prefix = "hello" %>
<%... @ Page contentType = "text/html; charset = GBK" language = "java" %>
<Html>
<Head>
<Title> first tag </title>
<Meta http-equiv = "Content-Type" content = "text/html; charset = GBK">
</Head>
<Body>
<P> the following content is output from Taglib: </p>
<P> <my: hello> </p>
</Body>
</Html>
I hope this article will help you.