Custom Tag Iteration Example

IterationTag interface is used to handle the iteration in custom tag rather than JSP page. Control flow is handled cleanly in Java classes to improve maintainability of JSP page . IterationTag interface has a single method int doAfterBody () to handle the iteration and return vale EVAL_BODY_AGAIN until the list has been completed.
  1. Tag handler class : The Tag handler class extends TagSupport class and perform action.
  2. TLD (Tag Library Descriptor) file : A TLD file is an XML document with a .tld extension that describes one or more tag extensions.
  3. JSP file : This file is created to use custom tag which are defined in the TDL file.
Custom Tag Iteration Example using Tomcat6.0
InputNameTag.java
package ns; import java.util.List; import javax.servlet.jsp.JspTagException; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.tagext.TagSupport; public class InputNameTag extends TagSupport { private List name; private int i; public List getName() { return name; } public void setName(List name) { this.name = name; } public int doStartTag() throws JspTagException { setNameVariable(); return EVAL_BODY_INCLUDE; } public int doAfterBody()throws JspTagException { setNameVariable(); return EVAL_BODY_AGAIN; } public int doEndTag() throws JspTagException { try { JspWriter out=pageContext.getOut(); out.print("Custom Tag processing Iteration Example"); out.print("<br>"); out.println("User Name :" + name); } catch(Exception e) { } return EVAL_PAGE; } public void setNameVariable() { pageContext.setAttribute("name", name.get(i).toString()); } }
inputName.tld
<?xml version="1.0" encoding="UTF-8"?> <taglib> <tlib-version>1.0</tlib-version> <jsp-version>1.2</jsp-version> <short-name>hello</short-name> <uri>inputName.tld</uri> <tag> <name>example</name> <tag-class>ns.InputNameTag </tag-class> <body-content>EMPTY</body-content> <attribute> <name>name</name> <required> true </required> <rtexprvalue>true</rtexprvalue> </attribute> </tag> </taglib>
index.jsp
<%@ page import="java.util.*"%> <%@ taglib uri="inputName.tld" prefix="mytag" %> <html> <head> <title>Simple custom tag Iteration example </title> </head> <body> <%! public List name= new LinkedList(); public void jspInit() { name.add("Sunil"); name.add("Kumar"); name.add("Singh"); } %> Welcome to Iteration processing custom tag example <h1> <mytag:example name="<%=name %>"/> </h1> <br> <h2> <mytag:example name="<%=name %>" /> </h2> </body> </html>
Output
tag iteration

Download this example
1.) Deployed using Tomcat 6.0
2.) Deployed using Eclipse
 



 

Latest Tutorial


Most Visited Tutorial