We can iterate the body content of any tag using the doAfterBody()method of IterationTag interface.
Here we are going to use the TagSupport class which implements the IterationTag interface. For iterating the body content, we need to use the EVAL_BODY_AGAIN constant in the doAfterBody() method.
Example of Iteration using JSP Custom Tag
In this example, we are going to use the attribute in the custom tag, which returns the power of any given number. We have created three files here
- index.jsp
- PowerNumber.java
- mytags.tld
index.jsp
<%@ taglib uri="WEB-INF/mytags.tld" prefix="m" %> 3 ^ 5 = body
PowerNumber.java
package com.javatpoint.taghandler; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.tagext.TagSupport; public class PowerNumber extends TagSupport{ private int number; private int power; private static int counter; private static int result=1; public void setPower(int power) { this.power = power; } public void setNumber(int number) { this.number = number; } public int doStartTag() throws JspException { return EVAL_BODY_INCLUDE; } public int doAfterBody() { counter++; result *= number; if (counter==power) return SKIP_BODY; else return EVAL_BODY_AGAIN; } public int doEndTag() throws JspException { JspWriter out=pageContext.getOut(); try{ out.print(result); }catch(Exception e){e.printStackTrace();} return EVAL_PAGE; } }
mytags.tld
1.0 1.2 simple http://tomcat.apache.org/example-taglib A simple tab library for the examples power com.javatpoint.taghandler.PowerNumber number true power true
Looping using Iteration Tag (creating tag for loop)
Let’s create a loop tag that iterates the body content of this tag.
File: index.jsp
Insert title here <%@taglib prefix="m" uri="sssuri" %>
My Name is khan
File: mytags.tld
1.0 1.2 abc sssuri loop com.javatpoint.customtag.Loop start true end true
File: Loop.java
package com.javatpoint.customtag; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.TagSupport; public class Loop extends TagSupport{ private int start=0; private int end=0; public void setStart(int start) { this.start = start; } public void setEnd(int end) { this.end = end; } @Override public int doStartTag() throws JspException { return EVAL_BODY_INCLUDE; } @Override public int doAfterBody() throws JspException { if(start<end){ start++; return EVAL_BODY_AGAIN; }else{ return SKIP_BODY; } } }
File: web.xml
sssuri /WEB-INF/mytags.tld
Leave A Comment