3) 编写ElementoutTag ,把 Collection 中每个men对象的 name 打印出来
2. 完整程序如下:
在上例的diegoyun.vo包内,编写 People 类
package diegoyun.vo;
import java.util.Collection;
public class People
{
private Collection men = null;
public Collection getMen()
{
return men;
}
public void setMen(Collection men)
{
this.men = men;
}
}
编写 withObject ,这是从request里取得People对象的最外层Tag
package diegoyun;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;
import org.apache.taglibs.standard.lang.support.ExpressionEvaluatorManager;
public class WithObjectTag extends BodyTagSupport
{
private Object value = null;
public Object getValue()
{
return value;
}
public void setValue(Object value)throws JspException
{
this.value = ExpressionEvaluatorManager.evaluate("value", value.toString(), Object.class, this, pageContext);
}
public int doStartTag()
{
return EVAL_BODY_INCLUDE;
}
public int doEndTag()throws JspException
{
return EVAL_PAGE;
}
}
public class WithCollectionTag extends BodyTagSupport {
private Object element = null;
private Collection list = null;
private Iterator iterator = null;
public Object getElement() {
return element;
}
public void setProperty(String property) throws JspException {
//取得父Tag对象,并且得到Collection
WithObjectTag parent = (WithObjectTag) getParent();
if (parent == null)
throw new JspException("parent tag is null");
try {
Object propertyValue = PropertyUtils.getProperty(parent.getValue(),property);
this.list = (Collection) propertyValue;
if (list == null)
throw new JspException("Collection is null");
} catch (Exception e) {
throw new JspException(e);
}
}
public int doStartTag() throws JspException {
//设置第一个元素,然后执行子Tag
iterator = list.iterator();
if (iterator.hasNext())
element = iterator.next();
return EVAL_BODY_INCLUDE;
}
public int doAfterBody() {
if (iterator.hasNext()) {
//如果还存在子元素,设置子元素,并且再次执行子Tag
//循环由此而来
//否则不再执行子Tag
element = iterator.next();
return EVAL_BODY_AGAIN;
}
else
return EVAL_PAGE;
}
}