Custom tags are useful as they help in exposing business functionalities to page designers in a simple way. At runtime the tags are converted into java calls when the jsp page is translated into servlet.
There are two ways of developing tags:
We will look into the way of developing the tag logic using Java classes as it is more powerful and flexible and provides tool support at development time.
To implement a tag the first thing to do is to write a class which implements SimpleTag interface. However there is a utility class which can be used to extending our tag class and provides default implementation for the interface functions.
This class is a bean class having one property. Now we want to expose this tag and want to expose the property as an attribute of tag. For that we have to write a tld file and place it at WEB-INF/tlds folder. Let's put helloTag.tld helloTag.tld
Our tag is ready and raring to be used. Let's write a jsp where we use this tag.
Deploy your application and hit the jsp. When the jsp is translated into servlet the tag code is replaced with following:
Container calls the setJspContext() method to provide the context information in the form of JspContext instance. JspContext provides access to all the JSP scope variables and the current output stream for the page and it implements a number of utility methods the tag handler may use. In the tld you would have notices the we have written body-content is empty. It means is that we do not have body in the tag. That's the reason that in the trasnlated jsp code the setJspBody method is commented. When the body is presented it is set by calling the setJspBody.The body is treated as JspFragment and passed to the tag class by calling public void setJspBody(JspFragment body) The container calls this method with a reference to a JSP fragment representing the custom action body before calling the doTag(). Again if the custom action doesn’t have a body this method is not called at all. The body is evaluated by calling the invoke method on the JspFragment object. If we want to manipulate the body we have to pass a String writer to the invoke method. The body is written on the StringWriter which can than be manipulated.