pengfeng 发表于 2013-1-27 04:57:18

Struts2 OGNL遍历

OGNL是Object-Graph Navigation Language的缩写,它是一种功能强大的表达式语言(Expression Language,简称为EL),通过它简单一致的表达式语法,可以存取对象的任意属性,调用对象的方法,遍历整个对象的结构图,实现字段类型转化等功能。它使用相同的表达式去存取对象的属性。 
总的来说JSP页面中的元素<s:property value="xxx"/>,只要在action中有它对应的public Getter即可得到相应的值。 



<s:select label="label" name="name" list="{'name1','name2','name3'}" value="%{'name2'}" /> <s:select label="userList" name="userList" list="userList" listKey="id" listValue="name" /> // userList中为JavaBean <s:select label="'map'" name="mapList" list="map"/>  
选择(select)一个集合的子集(叫做投影),你可以在Collection中使用通配符. 
? -所有符合选择逻辑的元素 
^ - 符合选择逻辑的第一个元素 
$ - 符合选择逻辑的最后一个元素 
示例: 
JavaBean: 
Book.java 
private String title; 
private String author; 
private double price; 
Action: private List<Book> bookList; 
JSP页面: 
<s:iterator value="bookList.{?#this.price > 35}"> 
      <s:property value="title" /> :<s:property value="price" /> 
</s:iterator> 

Iterator 
<span style="line-height: normal; color: #000000;">
遍历List 
 

<s:iterator value="userList" status="status">//userList来自Action的public List getUserList()得到,无参的Getter,且修饰符一定为public      <s:set name="user"/>      <s:property value="name"/>      <s:property value="#user.name"/>//来自JSP页面的变量得用#引用      <s:property value="top.name"/>      <s:property value="top"/>      <s:property value="getValue(#user)"/>//getValue为Action中定义的public User getValue(User user) </s:iterator> 
遍历Map 

 

<s:iterator value="map" status="status">   <s:property value="key"/>   <s:property value="value"/></s:iterator> 
例子:

 

<s:iterator value="{'a','b','c'}" status="status" >      <s:property value="#status.index" />      <s:property value="#status.count-1" />      <s:property value="top" />-      <s:property value="'top'+#status.index+':'+top" /></s:iterator> 
输出: 
0 0 a- top0:a 
1 1 b- top1:b 
2 2 c- top2:c 

iterator 中status 的方法: 

even : boolean - returns true if the current iteration is even 
odd  : boolean - returns true if the current iteration is odd 
count : int - returns the count (1 based) of the current iteration 
index : int - returns the index (0 based) of the current iteration 
first : boolean - returns true if the iterator is on the first iteration 
last : boolean - returns true if the iteration is on the last iteration 
modulus(operand : int) : int - returns the current count (1 based) modulo the given operand 
eg:<s:property value="#stat.modulus(2)" /> 

IF 
 

<s:if test="#status.odd">class1</s:if><s:else>class2</s:else><s:if test="type=='Amount'||type==null"> display</s:if>//其中type相当<ww:property value="type" />  
页: [1]
查看完整版本: Struts2 OGNL遍历