JSP Custom Tags: Bringing Components to the Web - Creating a Custom Tag, Step By Step (Page 2 of 4 )
There are two main steps in creating a custom tag: creating the tag handler, and creating the TLD file.
As discussed in the previous section, a tag handler is nothing but a Java class and the TLD file is a mapping document written in XML format.
Creating the Tag Handler
A tag is defined in a tag handler. It extends either the TagSupport or BodySupport class. Both of these provide default implementations for the following methods:
If the tag handler has:
You need to implement the following methods:
no attributes and no body attributes
doStartTag, doEndTag, release doStartTag, doEndTag, set/getAttribute (all the attributes)
So if a Simple Tag has to be created, the class template would look like this:
package someorg.examples import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; /** * This is a simple tag example to show how content is added to the * output stream when a tag is encountered in a JSP page. */ public class Hello extends TagSupport { //define variables for attributes /** * Getter/Setter for the attribute name as defined in the tld file * for this tag
*/ /** * doStartTag is called by the JSP container when the tag is encountered */ public int doStartTag() { try { JspWriter out = pageContext.getOut(); //Content to be output by the tag // Must return SKIP_BODY because if body content execution is not supported for this // tag. return SKIP_BODY; } /** * doEndTag is called by the JSP container when the tag is closed */ public int doEndTag(){ try { JspWriter out = pageContext.getOut ();
// } catch (Exception ex){ throw new Error("All is not well in the world."); } } }
From the above template, the following points are clear:
The tag handler must extend the TagSupport class if the basic tag is to be created.
The variables that will act as the holders of attribute values have to be declared. For example, if the tag is <hello /> and contains an attribute called "name" i.e.<hello name="blah"/>, then the handler should have a variable called name.
Getters and setters must be defined for the attribute variable.
The logic for the content to be produced is implemented in doStartTag() and doEndTag() methods. The logic in doStartTag() is executed when the start of a tag (for example <hello>) is encountered. And the logic in doEndTag() is executed when a tag is closed (for example </hello>).
If the contents of the body must be executed, then the return of the doStartTag() must be BODY_EVAL, and if not, then BODY_SKIP.
The release() method need not be overridden because its default implementation is sufficient for most purposes.
That is how a tag handler is written. The next step is to map all the above information into a TLD file so that the JSP container can validate and call the appropriate methods and handlers if more than one handler is present.