IterationTag interface of Tag API

In this post, you will learn:

  • What is the role of IterationTag interface in Tag API?
  • How to define a custom tag using IterationTag?

IterationTag interface:

IterationTag is a sub interface of Tag. It adds following method to the tag life cycle:

doAfterBody: This method facilitate iterative processing of tag body i.e. processing of the body more than once. It is invoked by the Tag processor only if the tag has non empty body and doStartTag() method returns EVAL_BODY_INCLUDE. It has following syntax:

public int doAfterBody();

This method returns an integer which tells the Tag Processor whether the body is to be processed again or not. Following static final integer data members can be used as its return value: IterationTag.EVAL_BODY_AGAIN and Tag.SKIP_BODY. When Tag.SKIP_BODY is returned by this method only then doEndTag() method is invoked by the Tag processor.

TagSupport helper class implements this interface i.e. a custom Tag class which extends TagSupport can get its body processed multiple times.

The following application demonstrates the use of IterationTag interface.

The RepeaterTag class:

package com.techmentro.learningpad;

import javax.servlet.jsp.tagext.*;

public class RepeaterTag extends TagSupport {

	int counter;
	public void setCounter (String c)
	public int doStartTag()
	public int doAfterBody()
		return SKIP_BODY;	

The HelloTag class:

package com.techmentro.learningpad;

import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;

public class HelloTag extends TagSupport {

	//data member to store attribute value
	private String user;
	//setter method to set the value of attribute
	public void setUser(String user) {
		this.user = user;
	//to display welcome message for the user
	public int doEndTag()
		JspWriter out=pageContext.getOut();
		out.println("Welcome, "+user+"<br/>");
		}catch(Exception ex)
		return EVAL_PAGE;

The TLD file:




The index.html page:

<form action="home.jsp">
Name <input type="text" name="name"><br/>
<input type="submit" value="submit">

The home.jsp:

<%@ taglib uri="techmentro/tags" prefix="tm" %>

String uname=request.getParameter("name");

<tm:repeat counter="5">
<tm:hello user="<%=uname %>"/>


The welcome message is presented to the user 5 times by the custom tag.

Its time to recap the main concepts:

  1. IterationTag interface facilitate iterative processing of the Tag body.
  2. With the help of this interface custom tags can be defined to simulate the loops or to iterate the collection elements.
  3. It adds doAfterBody() method to the life cycle.
  4. It also defines EVAL_BODY_AGAIN static final int data member to be used as the return value of the doAfterBody() method.

Example Source Code

If you like the post, then share it...Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn

Leave a Reply

Your email address will not be published. Required fields are marked *