Different Types of Tags and Their Life Cycle in JSP

Different Types of Tags and Their Life Cycle in JSP

In this article, I am going to discuss Different Types of Tags and Their Life Cycle in JSP with Examples. Please read our previous article where discussed JSP Custom Tags. At the end of this article, you will understand the following pointers.

  1. Different Types of Tags and Their Life Cycle in JSP
  2. Classic Tags in JSP
  3. Tag Interface: Methods, Fields, Life Cycle, and Example of Tag Interface in JSP
  4. Iterator Tags: Methods, Fields, Life Cycle, and Example of Iterator Tag in JSP
  5. Nested Tags in JSP with Example
  6. Body Tags: Methods, Fields, Life Cycle, and Example of Body Tag in JSP
  7. Simple Tag: Methods, Fields, Life Cycle, and Example of Simple Tag in JSP
  8. Attributes of Custom Tag
Tags and its Life Cycle

To design Tag Handler classes in custom tags preparation JSP API has provided some predefined library in the form of javax.servlet.jsp.tagext package (tagext -> tag extension). javax.servlet.jsp.tagext package has provided the following library to design TagHandler classes.

Different Types of Tags and Their Life Cycle in JSP

As per the tag library provided by JSP technology, there are 2 types of custom tags:

  1. Classic tags
  2. Simple tags
Classic Tags in JSP

Classic tags are the custom tags which implements the javax.servlet.jsp.tagext.Tag interface. There are three types of classic tags:

  1. Simple Classic tags
  2. Iterator tags
  3. Body tags
Simple Classic Tags in JSP

It is designed on the basis of the Classic tag library provided by JSP API. javax.servlet.jsp.tagext.TagSupport is its subinterfaces or overrides classes which has a default implementation. Simple Classic Tags does not have a body and attribute list. To design simple classic tags the respective TagHandler class must implement the Tag interface either directly or indirectly.

public interface Tag extends JspTag
{
public static final int EVAL_BODY_INCLUDE;
public static final int SKIP_BODY;
public static final int EVAL_PAGE;
public static final int SKIP_PAGE;
public void setPageContext(PageContext pageContext);
public void setParent(Tag t);
public Tag getParent();
public int doStartTag() throws JspException;
public int doEndTag() throws JspException;
public void release();
}

public class MyHandler implements Tag
{
 	………………..
        ………………….
}
Tag Interface in JSP

It is the sub-interface of the JspTag Interface which provides methods to perform the action at the start and end tag of the tag.

Methods of Tag Interface
  • setPageContext(_): This method is to inject the pageContext implicit object into the present TagHandler class.
  • setParent(_): This method is to inject the parent tags TagHandler class object into the present TagHandler class.
  • getParent(_): This method is used to return the parent tags TagHandler class object from the TagHandler class.
  • doStartTag(): This method is used to perform a particular action when the container encounters the start tag of the custom tag. After the start tag evaluating the custom tag body is completely depends on the return value provided by the doStartTag() method.
  • doEndTag(): This method is used to perform an action when the container encounters the end tag of the custom tag. The custom tag body is not completely dependent upon the return value provided by the doEndTag() method.
  • release(): This method is used to perform TagHandler class de-instantiation.
Fields of Tag Interface

There are two possible return values from doStartTag() method:

  1. EVAL_BODY_INCLUDE: When the doStartTag() returns this constant, the container will evaluate the custom tag body.
  2. SKIP_BODY: When the doStartTag() returns this constant, the container will skip the custom tag body and encounter the end tag.

There are two possible return values from the doEndTag() method:

  1. EVAL_PAGE: When the doEndTag() returns this constant, the container will evaluate the remaining JSP page.
  2. SKIP_PAGE: When the doEndTag() returns this constant, the container will not evaluate the remaining JSP page.
Life Cycle of Tag Interface in JSP

Life Cycle of Tag Interface in JSP

The tags may have the default values, therefore the default values are read and then setPageContext(), setParent(), and therefore the setters of all the attributes are invoked. After the initialization of all the properties doStartTag() method is invoked. It may return SKIP_BODY or EVAL_BODY_INCLUDE. The doEndTag() is named if and as long as the tag ends normally without raising an exception. Some setters could also be called again before the tag handler is reused. Once all invocations on the tag handler are completed, the release() method is invoked thereon. Once a release method has invoked all properties, including parent and pageContext, are assumed to possess been reset to an unspecified value. The page compiler guarantees that release() is going to be invoked on the Tag handler before the handler is released to the GC.

Tag Interface Example in JSP:

In this example, we are creating a custom tag MyTags which will display the messageHello….. First Custom Tag Application” when used on JSP page. HelloHandler.java is a tag handler class which is implementing Tag interface. The hello.tld file should present the location “WEB-INF” and should have .tld extension where we have created a custom tag named mytags.

hello.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
 <%@taglib uri="WEB-INF/hello.tld" prefix="mytags"%>
 <mytags:hello />
</body>
</html>
hello.tld
<?xml version="1.0" encoding="UTF-8"?>
<taglib>
 <jsp-version>2.1</jsp-version>
 <tlib-version>1.0</tlib-version>
 <tag>
  <name>hello</name>
  <tag-class>Action.HelloHandler</tag-class>
  <body-content>jsp</body-content>
 </tag>
</taglib>
HelloHandler.java
package Action;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
public class HelloHandler implements Tag{
 PageContext pageContext;
 public void setPageContext(PageContext pageContext)
 {
  this.pageContext=pageContext;
  System.out.println("setPageContext()");
  
 }
 public void setParent(Tag t) {
  System.out.println("setParent()");
 }
 public Tag getParent() {
  System.out.println("getParent()");
  return null;
 }
 public int doStartTag() throws JspException
 {
  try {
   System.out.println("doStartTag()");
   JspWriter out=pageContext.getOut();
   out.println("<h1>Hello..... First Custom Tag Application</h1>");
  }
  catch(Exception e)
  {
   e.printStackTrace();
  }
  return SKIP_BODY;
 }
 public int doEndTag() throws JspException{
  System.out.println("doEndTag()");
  return SKIP_PAGE;
 }
 public void release() {}
}
Output

Run your hello.jsp page to get the following output.

Tag Interface Example in JSP

You will get the following output in the console.

Different Types of Tags and Their Life Cycle in JSP

Iterator Tags in JSP

To prepare iterator tags the respective TagHandler class must implement javax.servlet.jsp.tagext.IterationTag interface. It retrieves objects stored in JavaBeans components and assigns them to a variable and then the body of the tag retrieves information from that variable. The iteration tag causes the body to be reevaluated as long as elements remain in the collection.

public interface IterationTag extends Tag
{
public static final int EVAL_BODY_INCLUDE;
public static final int SKIP_BODY;
public static final int EVAL_PAGE;
public static final int SKIP_PAGE;
public static final int EVAL_BODY_AGAIN;
public void setPageContext(PageContext pageContext);
public void setParent(Tag t);
public Tag getParent();
public int doStartTag() throws JspException;
public int doAfterBody() throws JspException;
public int doEndTag() throws JspException;
public void release();
}

public class MyHandler implements IterationTag
{
………………..
………………….
}
Methods of Iteration Tag
  • setPageContext(_): This method is to inject the pageContext implicit object into the present TagHandler class.
  • setParent(_): This method is to inject the parent tags TagHandler class object into the present TagHandler class.
  • getParent(_): This method is used to return the parent tags TagHandler class object from the TagHandler class.
  • doStartTag(): This method is used to perform a particular action when the container encounters the start tag of the custom tag. After the start tag evaluating the custom tag body is completely depends on the return value provided by the doStartTag() method.
  • doAfterBody(): The container will access this method after evaluating the custom tag body.
  • doEndTag(): This method is used to perform an action when the container encounters the end tag of the custom tag. The custom tag body is not completely dependent upon the return value provided by the doEndTag() method.
  • release(): This method is used to perform TagHandler class de-instantiation.
Fields of Iterator Tag

There are two possible return values from doStartTag() method:

  1. EVAL_BODY_INCLUDE: When the doStartTag() returns this constant, the container will evaluate the custom tag body.
  2. SKIP_BODY: When the doStartTag() returns this constant, the container will skip the custom tag body and encounter the end tag.

There are two possible return values from doAfterBody() method:

  1. EVAL_BODY_AGAIN: When the doAfterBody() returns this constant, the container will execute the custom tag body again.
  2. SKIP_BODY: When thedoAfterBody() returns this constant, the container will skip out custom tag body evaluation and encounter the end tag of the custom tag.

There are two possible return values from the doEndTag() method:

  1. EVAL_PAGE: When the doEndTag() returns this constant, the container will evaluate the remaining JSP page.
  2. SKIP_PAGE: When the doEndTag() returns this constant, the container will not evaluate the remaining JSP page.
Life Cycle of Iteration Tag in JSP

The tags may have the default values, therefore the default values are read and then setPageContext(), setParent(), and therefore the setters of all the attributes are invoked. After the initialization of all the properties doStartTag() method is invoked. It may return SKIP_BODY or EVAL_BODY_INCLUDE. If EVAL_BODY_INCLUDE is returned, and therefore the custom action element isn’t empty, the body is evaluated and “passed through” to the present out, then doAfterBody() is invoked and, after zero or more iterations, doEndTag() is invoked. The doEndTag() is named if and as long as the tag ends normally without raising an exception. Some setters could also be called again before the tag handler is reused. Once all invocations on the tag handler are completed, the release() method is invoked thereon. Once a release method has invoked all properties, including parent and pageContext, are assumed to possess been reset to an unspecified value.

Life Cycle of Iteration Tag in JSP

This approach will increase the burden to the developers and unnecessary methods in TagHandler classes. To overcome the above problem JSP API has provided an alternative in the form of TagSupport class.

TagSupport Class

TagSupport class is a concrete class, which was implemented Tag and IterationTag interfaces with the default implementation. If we want to prepare custom tags with the TagSupport class then we have to take a user-defined class, which must be a subclass to TagSupport class. Below is the typical method invocation sequence:

public interface TagSupport extends IterationTag
{
public static final int EVAL_BODY_INCLUDE;
public static final int SKIP_BODY;
public static final int EVAL_PAGE;
public static final int SKIP_PAGE;
public static final int EVAL_BODY_AGAIN;
public PageContext pageContext;
public Tag t;
public void setPageContext(PageContext pageContext){
  this.pageContext=pageContext;
}
public void setParent(Tag t){
  this.t=t;
}
public Tag getParent(){
  return t;
}
public int doStartTag() throws JspException{
  return SKIP_BODY;
}
public int doAfterBody() throws JspException{
return SKIP_BODY;
}
public int doEndTag() throws JspException{
  return EVAL_PAGE;
}
public void release(){}
}

public class MyHandler implements IterationTag
{
………………..
………………
}
}
Iterator Tags Example in JSP

In this example, we are creating a custom tag MyTags which will display the messageHello World” when used on the JSP page. Here we are creating a loop tag that iterates the body content of this tag 10 times. Iteration.java is a tag handler class which is extending TagSupport. The iterate.tld file should present the location “WEB-INF” and should have a .tld extension where we have created a custom tag named mytags.

iterate.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%@taglib uri="WEB-INF/iterate.tld" prefix="mytags" %>
<mytags:iterate times="10"><br>
 Hello World
</mytags:iterate>
</body>
</html>
iterate.tld
<?xml version="1.0" encoding="UTF-8"?>
<taglib>
 <jsp-version>2.1</jsp-version>
 <tlib-version>1.0</tlib-version>

 <tag>
  <name>iterate</name>
  <tag-class>Action.Iteration</tag-class>
  <body-content>jsp</body-content>
  <attribute>
   <name>times</name>
   <required>true</required>
   <rtexprvalue>true</rtexprvalue>
  </attribute>
 </tag>
</taglib>  
Iteration.java
package Action;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
public class Iteration extends TagSupport {
 int count=1;
 private int times;
 public void setTimes(int times) {
  this.times=times;
 }
 public int doStartTag() throws JspException{
  return EVAL_BODY_INCLUDE;
 }
 public int doAfterBody() throws JspException{
  if(count<times) {
   count++;
   return EVAL_BODY_AGAIN;
  }
  else {
   return SKIP_BODY;
  }
 }
}
Output

Iterator Tags Example in JSP

Nested Tags in JSP

The Nested Tag is defining a tag inside a tag. It is a child tag that can access parent tag by using the setParent() method. By using nested tags we can perform more complex functions. If we are using a nested tag then we have to provide a separate configuration in the TLD file and we have to prepare a separate tag handler class under the classes folder.

Example of Nested Tag in JSP

In NestedTag.jsp page, the mytags:if tag is used where a value of true and false is hardcoded for the condition. Here we have defined mytags to handle the mytags:if tag. This handler should have methods to specify and check whether the condition is true or false as well as methods to designate and check if the condition has ever been explicitly set. In NestedTag.tld page, the nesting validation is performed only at request time, not at page translation time.

NestedTag.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <?xml version="1.0"?>

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%@taglib uri="/WEB-INF/NestedTag.tld" prefix="mytags" %>
<h1>
<mytags:if condition='<%=10>20%>' >
<mytags:true>condition is true</mytags:true>
<mytags:false>condition is false</mytags:false>
</mytags:if>
</h1>

</body></html>
NestedTag.tld
<?xml version="1.0" encoding="UTF-8"?>
<taglib>
 <tlib-version>1.0</tlib-version>
 <jsp-version>2.1</jsp-version>
 <short-name>Nested tag</short-name>
 <tag>
  <name>if</name>
  <tag-class>Action.If</tag-class>
  <body-content>jsp</body-content>
  <attribute>
   <name>condition</name>
   <required>true</required>
   <rtexprvalue>true</rtexprvalue>
  </attribute>
 </tag>
 <tag>
  <name>true</name>
  <tag-class>Action.True</tag-class>
  <body-content>jsp</body-content>
 </tag>
 <tag>
  <name>false</name>
  <tag-class>Action.False</tag-class>
  <body-content>jsp</body-content></tag>
</taglib>
If.java
package Action;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;

public class If extends TagSupport {
 private boolean condition;
 public void setCondition(boolean condition)
 {
  this.condition=condition;
 }
 public boolean getCondition()
 {
  return condition;
 }
 public int doStartTag() throws JspException
 {
  return EVAL_BODY_INCLUDE;
 }
}
True.java
package Action;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
public class True extends TagSupport {
 public int doStartTag() throws JspException
 {
  If i=(If)getParent();
  boolean condition=i.getCondition();
  if(condition == true)
   return EVAL_BODY_INCLUDE;
  else
   return SKIP_BODY;
 }
}
False.java
package Action;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
public class False extends TagSupport {
 public int doStartTag() throws JspException
 {
  If i=(If)getParent();
  boolean condition=i.getCondition();
  if(condition == true)
   return SKIP_BODY;		
  else
   return EVAL_BODY_INCLUDE;
 }
}
Output

Example of Nested Tag in JSP

Body Tags in JSP

To perform updations over the custom tag body we have to use Body Tags. To design body tags in JSP technology then the respective TagHandler class must implement javax.servlet.jsp.tagext.BodyTag interface. It provides a BodyTagSupport class which provides default empty methods defined in the interface. Below is the typical method invocation sequence:

public interface BodyTag extends IterationTag
{
public static final int EVAL_BODY_INCLUDE;
public static final int SKIP_BODY;
public static final int EVAL_PAGE;
public static final int SKIP_PAGE;
public static final int EVAL_BODY_AGAIN;
public static final int EVAL_BODY_BUFFERED;
public void setPageContext(PageContext pageContext);
public void setParent(Tag t);
public Tag getParent();
public int doStartTag() throws JspException;
public int doInitBody() throws JspException;
public void setBodyContent(BodyContent bodyContent);
public int doAfterBody() throws JspException;
public int doEndTag() throws JspException;
public void release();
}

public class MyHandler implements BodyTag
{
………………..
………………….
}
Methods of Body Tag
  • setPageContext(_): This method is to inject the pageContext implicit object into the present TagHandler class.
  • setParent(_): This method is to inject the parent tags TagHandler class object into the present TagHandler class.
  • getParent(_): This method is used to return the parent tags TagHandler class object from the TagHandler class.
  • doStartTag(): This method is used to perform a particular action when the container encounters the start tag of the custom tag. After the start tag evaluating the custom tag body is completely depends on the return value provided by the doStartTag() method.
  • setBodyContent(): By using this method, the container will prepare the BodyContent object with the buffer.
  • doInitBody(): After executing setBodyContent() method, container will access doInitBody() method in order to prepare BodyContent object for allow modifications.
  • doAfterBody(): The container will access this method after evaluating the custom tag body.
  • doEndTag(): This method is used to perform an action when the container encounters the end tag of the custom tag. The custom tag body is not completely dependent upon the return value provided by the doEndTag() method.
  • release(): This method is used to perform TagHandler class de-instantiation.
Fields of Body Tag in JSP

There are two possible return values from doStartTag() method:

  1. EVAL_BODY_INCLUDE: When the doStartTag() returns this constant, the container will evaluate the custom tag body.
  2. SKIP_BODY: When the doStartTag() returns this constant, the container will skip the custom tag body and encounter the end tag.
  3. EVAL_BODY_BUFFERED: The container will store the custom tag body in a buffer then access the setBodyContent() method if we return EVAL_BODY_BUFFERED constant.

There are two possible return values from doAfterBody() method:

  1. EVAL_BODY_AGAIN: When the doAfterBody() returns this constant, the container will execute the custom tag body again.
  2. SKIP_BODY: When the doAfterBody() returns this constant, the container will skip out custom tag body evaluation and encounter the end tag of the custom tag.

There are two possible return values from the doEndTag() method:

  1. EVAL_PAGE: When the doEndTag() returns this constant, the container will evaluate the remaining JSP page.
  2. SKIP_PAGE: When the doEndTag() returns this constant, the container will not evaluate the remaining JSP page.
Life Cycle of Body Tag in JSP

Here, IterationTag extends the Tag interface and adds one new method doAfterBody() that controls the reevaluation of its body. doAfterBody() method is invoked by the JSP Page implementation object after every evaluation of the body into the BodyEvaluation object. The method isn’t invoked if there’s nobody evaluation.

If doAfterBody returns EVAL_BODY_AGAIN, a new evaluation of the body will happen (followed by another invocation of doAfterBody). If doAfterBody returns SKIP_BODY, no more body evaluations will occur, and therefore the doEndTag method is going to be invoked. In BodyTag, there’s a replacement action method: doInitBody(), which is invoked right after setBodyContent() and before the body evaluation. This method is only invoked if doStartTag() returns EVAL_BODY_BUFFERED. If EVAL_BODY_BUFFERED is returned, then a BodyContent object is going to be created (by code generated by the JSP compiler) to capture the body evaluation.

Life Cycle of Body Tag in JSP

To use the above approach the respective TagHandler class must implement all the methods declared in the BodyTag interface irrespective of the application requirement which may increase the burden to the developers and unnecessary methods in the custom tag application. To overcome this problem we will use an alternative provided by JSP technology i.e. javax.servlet.jsp.tagext.BodyTagSupport class.

BodyTagSupport class

BodyTagSupport class is a concrete class which is a direct implementation class to javax.servlet.jsp.tagext.BodyTag interface. It provides the default implementation for all the methods declared in javax.servlet.jsp.tagext.BodyTag interface which provides default empty methods defined in the interface. Below is the typical method invocation sequence:

public interface BodyTagSupport extends BodyTag
{
public static final int EVAL_BODY_INCLUDE;
public static final int SKIP_BODY;
public static final int EVAL_PAGE;
public static final int SKIP_PAGE;
public static final int EVAL_BODY_AGAIN;
public static final int EVAL_BODY_BUFFERED;
public PageContext pageContext;
public Tag t;
public BodyContent bodyContent;
public void setPageContext(PageContext pageContext){
     		this.pageContext=pageContext;
}
public void setParent(Tag t){
     		this.t=t;
}
public Tag getParent(){
     		return t;
}
public int doStartTag() throws JspException{
     		return EVAL_BODY_BUFFERED;
}
public int doInitBody() throws JspException{}
public void setBodyContent(BodyContent bodyContent){
    		this.bodyContent=bodyContent;
}
public int doAfterBody() throws JspException{
     		return SKIP_BODY;
}
public int doEndTag() throws JspException{
    	 	return EVAL_PAGE;
}
public void release(){}
}

public class MyHandler implements BodyTagSupport
{
………………..
………………….
}

public String getString(): This method is used to get the custom tag body from the BodyContent object.

public JspWriter getEnclosingWriter(): This method is used to send modified data to the response object for which we have to get the JspWriter object from the BodyContent.

Body Tag Example in JSP

In this example, Reverse.java is a simple java file which is extending BodyTagSupport class. In this file, we have overridden only one method of BodyTagSupport,i.e. doEndTag() which performs an action when the container encounters an action on the end tag. Then, bodyContent.getString() is returning contents that are to be converted in Reverse order, and then it will be displayed on the browser. Then this method is returning EVAL_PAGE which is evaluating the remaining content of the JSP page. Here, reverse.tld file is an XML file which is setting the name, tagclass, and bodycontent of this tag and by using these parameters we are going to make use of it in out JSP page.

reverse.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
 <%@taglib uri="WEB-INF/reverse.tld" prefix="mytags"%>
 <mytags:reverse>Hello world</mytags:reverse>
</body>
</html>
reverse.tld
<?xml version="1.0" encoding="UTF-8"?>
<taglib>
 <jsp-version>2.1</jsp-version>
 <tlib-version>1.0</tlib-version>
 <tag>
  <name>reverse</name>
  <tag-class>Action.Reverse</tag-class>
  <body-content>jsp</body-content>
 </tag>
</taglib>
Reverse.java
package Action;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
public class Reverse extends BodyTagSupport{
 public int doEndTag() throws JspException{
  try {
   String data=bodyContent.getString();
   StringBuffer sb=new StringBuffer(data);
   sb.reverse();
   JspWriter out=bodyContent.getEnclosingWriter();
   out.println("<html>");
   out.println("<body bgcolor='lightyellow'>");
   out.println("<b><font size='7' color='red'");
   out.println("<br><br>");
   out.println(sb);
   out.println("</font></b></body></html>");
  }
  catch(Exception e) {
   e.printStackTrace();
  }
  return EVAL_PAGE;
 }
}
Output

Body Tag Example in JSP

Simple Tag in JSP

In the case of a simple tag library, all the TagHandler class objects are non-cacheable objects and all the custom tags are having body tags capacity by default. To design custom tags by using a simple tag library the respective TagHandler class must implement javax.servlet.jsp.tagext.Tag interface. The simple tags are as capable as classic tags but in simple tags, we cannot include scriptlet code in the body of a simple tag. Below is the typical method invocation sequence:

public interface SimpleTag extends JspTag{
 public void setJspContext(JspContext jspContext);
 public void setParent(JspTag t);
 public JspTag getParent();
 public void setJspBody(JspFragment jspFragment);
 public void doTag() throws JspException, IOException;
}
public class MyHandler implements SimpleTag{……….}

Here, jspContext is an implicit object available in the simple tag library which is used to make available all the JSP implicit objects. jspFragment is like bodyContent in classic tag library which will accommodate custom tag body directly.

Methods of SimpleTag
  1. setJspContext(): It is used to inject JspContext object into the present web application.
  2. setParent(): It is used to inject parent tags TagHandler class object reference into the present TagHandler class.
  3. getParent(): It is used to get parent tags TagHandler class object.
  4. setJspBody(): It is almost similar to setBodyContent() method in order to accommodate custom tag body.
  5. doTag(): It is equivalent to doStartTag() method an doEndTag() method in order to perform an action.
Life Cycle of Simple Tag in JSP

Simple tag handlers are created initially using a zero-argument constructor on the corresponding implementation class. The setJspContext() and setParent() methods are invoked on the tag handler. The setParent() method need not be called if the value being passed in is null. In the case of tag files, a JspContext wrapper is made in order that the tag file can appear to possess its own page scope. Calling getJspContext() must return the wrapped Jsp-Context. The value for each element is evaluated, and the corresponding bean property setter methods are invoked for each, in the order in which they appear in the body of the tag. The value for the body of the tag is determined, and if a body exists the setJsp-Body() method is called on the tag handler. The doTag() method is invoked. The implementation of doTag() performs its function, potentially calling other tag handlers (if the tag handler is implemented as a tag file) and invoking fragments. The doTag() method returns, and therefore the tag handler instance is discarded.

Life Cycle of Simple Tag in JSP

The TagHandler class must implement the SimpleTag interface to use this approach which will increase the burden to the developers and unnecessary methods in the custom tags. To overcome this problem JSP provides an alternative in the form of javax.servlet.jsp.tagext.SimpleTagSupport class.

SimpleTagSupport class

To design custom tags by using SimpleTagSupport class then the respective TagHandler class must be extended from javax.servlet.jsp.tagext.SimpleTagSupport class where we have to override the required methods. Below is the typical method invocation sequence:

public interface SimpleTag extends JspTag{
 private JspContext jspContext;
 private JspFragment jspFragment;
 private JspTag jspTag;
 public void setJspContext(JspContext jspContext){
  this.jspContext=jspContext;
}
 public void setParent(JspTag t){
  this.jspTag=jspTag;
}
 public JspTag getParent(){
  return jspTag;
}
 public void setJspBody(JspFragment jspFragment){
  this.jspFragment=jspFragment;
}
public JspFragment getJspBody(){
  return jspFragment;
}
public JspContext getJspContext(){
  return jspContext;
}

 public void doTag() throws JspException, IOException{}
}
public class MyHandler implements SimpleTagSupport{……….}
Simple Tag Example in JSP

Hello.jsp is a simple tag handler class for printing the simple message. It extends SimpleTagSupport and implements the doTag() method. We get the pageContext by calling getJspContext() and then we get a JspWriter from the PageContext by calling getOut() on the PageContext. This is the writer that allows us to write out content to out JSP page. We have placed hello.tld file inside the WEB-INF folder which is an XML file which is setting the name, tagclass, and bodycontent of this tag, and by using these parameters we are going to make use of it in out JSP page.

hello.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
 <%@taglib uri="WEB-INF/hello.tld" prefix="mytags"%>
 <mytags:hello />
</body>
</html>
hello.tld
<?xml version="1.0" encoding="UTF-8"?>
<taglib>
 <jsp-version>2.1</jsp-version>
 <tlib-version>1.0</tlib-version>
 <tag>
  <name>hello</name>
  <tag-class>Action.Hello</tag-class>
  <body-content>empty</body-content>
 </tag>
</taglib>
Hello.java
package Action;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
public class Hello extends SimpleTagSupport{
 public void doTag() throws JspException, IOException{
  getJspContext().getOut().println("<h1>Hello Simple Tag Application</h1>");	
 }
}
Output

Simple Tag Example in JSP

Attributes of Custom Tag

If we want to provide attributes in custom tags then we have to perform the following steps:

Define attribute in the custom tag.

Example: <mytags:hello name=”Manisha”/>

Provide attribute description in the respective TLD file.

To provide attribute description in the TLD file we have to use the following tags in the TLD file.

<taglib>
……….
<tag>
………
<attribute>
<name>attribute_name</name>
<required>true/false</required>
<rtexprvalue>true/false</rtexprvalue>
</attribute>
/tag>
</taglib>

Were,

  1. Attribute: This tag can be used to represent a single attribute in the tld file.
  2. Name: This tag will take the attribute name.
  3. Required: This tag is a Boolean tag used to specify whether the attribute is mandatory or optional.
  4. Rtexprvalue: This tag is used to specify whether the attribute accepts runtime values or not.
Declare a property and setter method in TagHandler class with the same name of the attribute defined in the custom tag.
public class MyHandler implements tag{
     private String name;
     public void setName(String name){
           this.name=name;
     }
     ………….
}

In the next article, I am going to discuss JSP Client Request with Examples. Here, in this article, I try to explain Tags and their Life Cycle in JSP with Examples. I hope you enjoy this Tags and their Life Cycle with Examples article.

Leave a Reply

Your email address will not be published.