本文已于2016年04月19日最新编辑并更新到:http://iyiguo.net/blog/2009/09/03/struts2-iterator-usage 欢迎点击访问
在说明s:iterator标签的使用前,先了解下struts2中的Value Stack。这里参考了webwork中对Value Stack的描述,由于struts2是在webwork的基础上进行升级的,因此webwork对于Value Stack的表述同样适用于struts2。在这里不描述Value Stack具体做什么,但有两点需要注意:
对于2举个例子说明。假定Value Stack包含了[model,action,others],那么
现在将开始介绍s:iterator的一些使用。以下代码片段均在开发环境eclipse3.4 wtp、tomcat5.5、jdk5上使用struts2.1.6测试通过。
1)、访问 days
defined List<String> days ["Monday","Thursday","Friday","Sunday"]
<s:iterator value="days"><s:property /></s:iterator>
2)、使用top 关键字使用(过滤掉Monday)
defined List<String> days ["Monday","Thursday","Friday","Sunday"]
<s:iterator value="days"> <s:if test="top!='Monday'"> <s:property /> </s:if> </s:iterator>
3)、使用 last / first关键字
defined String[][] aTs = { { "一", "二", "三", "四" },{ "一一", "二二", "三三", "四四"} };
<!--遍历二维数组,The trick here is to use 'top' as the value for the inner iterator--> <s:iterator value="aTs" status="of"> <s:if test="#of.last"><br/></s:if> <s:iterator value="top"> <!--亦可用[0].top替代。如果单纯用[0],则会同时打印该处栈对象信息--> <s:property /> </s:iterator> </s:iterator>
4)、使用 odd/ even关键字
下面的例子要实现每行输出颜色不同的效果。
defined List<String> days ["Monday","Thursday","Friday","Sunday"]
<!--奇数行显示为红色,偶数行显示为绿色--> <s:iterator value="days" status="offset"> <s:else> <s:if test="#offset.odd==true"> <li style="color: red" mce_style="color: red"><s:property /></li> </s:if> <s:else> <li><s:property /></li> </s:else> </s:else> </s:iterator>
5)、总结下,当声明iterator的status属性时,通过#statusName.method可以使用以下方法:
6)、最后再来看下在iterator中调用value stack的用法。
假定countries是一个List对象,每一个country有一个name属性和一个citys List对象,并且每一个city也有一个name属性。那么我们想要在迭代citys时访问所属country的name属性就的用如下方式:
<s:iterator value="countries"> <s:iterator value="cities"> <s:property value="name"/>, <s:property value="[1].name"/><br> </s:iterator> </s:iterator>