package mytag;

import java.util.Iterator;
import java.util.Vector;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.BodyTagSupport;

public class IterTag extends BodyTagSupport
{
    //Tag的名称
    private String name;
    //用于迭代的容器
    private Vector vector;
    //容器中的类型
    private String type;
    //容器的迭代子，这是一个临时变量，而不是这个Tag的一个属性
    private Iterator it;

    public void setVector(Vector v)
    {
        this.vector=v;
        it=v.iterator();
    }

    public void setName(String name)
    {
        this.name = name;
    }

    public void setType(String type)
    {
        this.type = type;
    }

    public int doStartTag() throws JspTagException
    {
        if(vector==null)
            return SKIP_BODY;
        else
            return next();
    }
    public int doAfterBody() throws JspTagException
    {
        return next();
    }

    public int doEndTag () throws JspTagException
    {
        try
        {
            if(bodyContent!=null)
                bodyContent.writeOut(bodyContent.getEnclosingWriter());
        }
        catch(Exception e)
        {
            throw new JspTagException(e.getMessage());
        }
	  release();
        return EVAL_PAGE;
    }

    //移动迭代子
    private int next()  throws JspTagException
    {
        if(it.hasNext())
        {
            pageContext.setAttribute(name,it.next(),PageContext.PAGE_SCOPE);
            return EVAL_BODY_BUFFERED;
        }
        return SKIP_BODY;
    }
}
