package com.acme.tag; import javax.servlet.jsp.JspTagException; import javax.servlet.jsp.PageContext; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.BodyTagSupport; import javax.servlet.jsp.tagext.IterationTag; import javax.servlet.jsp.tagext.Tag; import javax.servlet.jsp.tagext.TagSupport; import java.util.Collection; import java.util.Iterator; /** * A simple Tag that Iterates a given Collection * * @author Magnus Rydin */ public class IteratorTag extends TagSupport { private Iterator iterator; private String type; public IteratorTag() { super(); } /** * Method used by the JSP container to set the Collection to use. */ public void setCollection(Collection collection) { if (collection.size() > 0) //check that the Collection have elements iterator = collection.iterator(); } /** * Method used by the JSP container to set the type of the object * that the Tag will add to the PageContext */ public void setType(String type) { this.type = type; } public int doStartTag() throws JspException { if (iterator != null) { if (hasNext()) return EVAL_BODY_INCLUDE; } return SKIP_BODY; } public int doAfterBody() throws JspException { if (hasNext()) return EVAL_BODY_AGAIN; else return SKIP_BODY; } private boolean hasNext() { if (iterator.hasNext()) { this.pageContext.setAttribute(id, iterator.next(), PageContext.PAGE_SCOPE); return true; } return false; } }