package mytag;

import java.io.IOException;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.BodyContent;
import javax.servlet.jsp.tagext.BodyTagSupport;

public class MyBodyTag extends BodyTagSupport
{
    //页面的上下文环境
    private PageContext context;

    //设置页面的上下文环境
    public void setPageContext(PageContext arg0)
    {
        this.context=arg0;

    }

    //构造方法，仅执行父类的构造方法
    public MyBodyTag()
    {
        super();
    }

    //number属性，设置标签主体的处理次数
    int number;

    //设置number属性
    public void setNumber(int n)
    {
        number=n;
    }

    //标签开始
    public int doStartTag()throws JspTagException
    {
        try
        {
            context.getOut().write("开始处理标签<br>");
            if(number>0)
            {
                context.getOut().write("开始处理标签体<br>");
                return EVAL_BODY_BUFFERED;
            }
            else
            {
                context.getOut().write("无需处理标签体<br>");
                return SKIP_BODY;
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return SKIP_BODY;
    }

    //一次主体处理结束后调用
    public int doAfterBody()throws JspTagException
    {
         try
            {
                context.getOut().write("系统当前时间：");
                context.getOut().write(new Long(System.currentTimeMillis()).toString()+"<br>");
wait(10);
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
            number--;
            if(number>0)
            {
                return EVAL_BODY_BUFFERED;
        }
        else
        {
            return SKIP_BODY;
        }
    }

    //标签结束
    public int doEndTag()throws JspTagException
    {
       try
       {
           if(bodyContent!=null)
           {
               bodyContent.writeOut(bodyContent.getEnclosingWriter());
           }
           context.getOut().write("结束处理标签<br>");
       }
       catch(Exception e)
       {
           throw new  JspTagException(e.getMessage());
       }
	 release()；
       return EVAL_PAGE;
    }

    //标签主体初始化
    public void doInitBody()
    {
        try
        {
            context.getOut().write("标签主体初始化<br>");
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }

    //设置标签主体
    public void setBodyContent(BodyContent body)
    {
        try
        {
            context.getOut().write("设置标签主体<br>");
            this.bodyContent=body;
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
//释放标签资源
    public void release()
    {
        try
        {
            context.getOut().write("释放标签资源<br>");
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        super.release();
    }
}
