1、问题:在request里的 people 对象,有个属性叫 men ,men 是一个collection ,有许多个man 。现在,把 collection里的man的名字都显示出来。
显然,这是一个嵌套tag的问题。有三个tag互相作用:最外层的tag找到people对象,中间的tag取得collection,子tag负责打印。
例如:
| <diego:withobject value=”${people}”> <diego:withcollection property=”men”> <diego:elementout property=”name”/> </diego:withcollection> </diego:withobject> |
思路如下:
1) 编写withobjecttag,负责从el表达式中取得对象
2) 编写withcollectiontag,负责从对象中取得 collection ,遍历 collection ,每遍历一次 collection ,执行一次body
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() |
编写withcollectiontag,该tag负责取得collection,并遍历执行子tag
| package diegoyun;
import java.util.collection; import javax.servlet.jsp.jspexception; import org.apache.commons.beanutils.propertyutils; public class withcollectiontag extends bodytagsupport { private collection list = null; private iterator iterator = null; public object getelement() { public void setproperty(string property) throws jspexception { public int dostarttag() throws jspexception { public int doafterbody() { |
编写 elementoutputtag
| package diegoyun; import java.io.ioexception; import javax.servlet.jsp.jspexception; import org.apache.commons.beanutils.propertyutils; public class elementoutputtag extends tagsupport |
编写tld
| <!–withobjecttag–> <tag> <name>withobject</name> <tag-class>diegoyun.withobjecttag</tag-class> <body-content>jsp</body-content> <attribute> <name>value</name> <required>false</required> <rtexprvalue>true</rtexprvalue> </attribute> </tag> <!–withcollectiontag–> <tag> <name>withcollection</name> <tag-class>diegoyun.withcollectiontag</tag-class> <body-content>jsp</body-content> <attribute> <name>property</name> <required>false</required> <rtexprvalue>true</rtexprvalue> </attribute> </tag> <!–elementoutputtag–> <tag> <name>elementout</name> <tag-class>diegoyun.elementoutputtag</tag-class> <body-content>empty</body-content> <attribute> <name>property</name> <required>false</required> <rtexprvalue>true</rtexprvalue> </attribute> </tag> |
编写jsp
| <%@ page language=”java” %> <%@ page import=”diegoyun.vo.*”%> <%@ page import=”java.util.*”%> <%@ taglib uri=”/web-inf/tlds/diego.tld” prefix=”diego”%> <html> man man1 = new man(); man man2 = new man(); man man3 = new man(); people p =new people(); |
运行,则可以看到:
| test loop tag: diego zidane rui |
