The process of developing and using JSP custom tags:
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;
Private tag parent;
Public hellotag ()...{
Super ();
}
/***//**
* Set the tab Page Context
* @ Param pagecontext
*/
Public void setpagecontext (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. Compile the tag library description.
Create a new mytag. TLD file in 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.
Add the following content 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 JSP files.
Compile the mytag. jsp file:
<%... @ Taglib uri = "/mytag" prefix = "hello" %>