In JSP we have a tag directive < %@ taglib uri='/web-inf/tag' prefix='mytag' %>
we invoke custom tag by
The uri specifies where to find the tag named "savemoney" ie in which .tld file.
tld file that is tag library descriptor tells us which class is associated with this tag.
Till now the picture is clear. We have a JSP file from which we invoke a custom Tag. This tag is mapped to a java file. The mapping is done in .tld file.
Now we have to write our tag handler class ie the java class which is the backbone of our Tag.
We have two options in which we can write Tag handler class.
- Simple Tag API
- Classic Tag API
This is the easiest way to write tag handler class. Once you understand it, you will love writing custom tags and handler classes.
SimpleTag is an interface which has methods defined in order to process tag. It contains methods like doTag, getParent, setPatent. getJspBody etc. As a developer we just need to extend SimpleTagSupport Class which implements SimpleTag Interface.
So we have :
So when we invoke the tag in a jsp page, the doTag method of the class associated with the tag is called.
Our tag handler has access to JSP implicit objects and get them using JspContext Object.
If the tag has a body the we can execute the body within doTag() via call to getJspBody().invoke(null).
If some exception occurs in the tag which will stop the tag execution we have SkipPageException. This will stop the execution of the page in which our tag is invoked.
So it is that simple to write a custom tag using SimpleTag interface.
Classic Tag handlers
There is no need to write the tags using classic tag handler but one should understand the way it is written. One can land up in a situation where he has to examine the code written by some other developer and he may have used classic tag.
We write a class which extends TagSupport Class. TagSupport class implements IterationTag interface. Itertion Tag interface implements Tag interface. We have methods like doStartTag, doEndTag, doAfterBody etc.
We have various Constants defined like SKIP_PAGE, SKIP_BODY, EVAL_BODY_INCLUDE, EVAL_PAGE which decides the execution of body, page.
So now you now how easy it is to develop custom tags. Don't be afraid of custom Tags because "dar ke aage jeet hai".