一、OGNL处理不同对象的属性是不一样的。
1. Map的属性就是key
2. Lists和Array的属性就是下标index
3. String的属性也是下标
4. 普通对象只能处理string属性,这个属性具有set/get或is/set方法。
属性名可以是任何类型,而不仅仅是“字符串类型的名字”(注意区别属性名和属性值的类型,这里是说这个属性的名字可以是非字符串的,例如这个属性的名字可以是一个数字),对于非字符串类型的属性名,我们访问属性值的时候要用下标的形式。例如对一个数组array:
它的长度是array的一个属性,这个属性名字叫做length,这个名字是一个字符串,因此可以用下面的方式访问:
array.length
现在要访问第0个元素,那么这个属性名是0,它是数字,应该按下下标方式访问
array[0]
为什么要将下标也作为属性呢?暂时做为一个未解决的问题!
OGNL内部是将
array.length
做为
array[“length”]
形式的,同时也等价于
array[“len”+”gth”]
二、OGNL与java代码中属性的下标访问
在java代码中,按index访问属性的模型如下:
public PropertyType[] getPropertyName()
public void setPropertyName(PropertyType[] anArray)
public PropertyType getPropertyName(int index)
public void setPropertyName(int index, PropertyType value)
在OGNL中可以通过index来无缝地访问,用下面的方式:
someProperty[2]
这样将自动调用getSomeProperty(2)或者是setSomeProperty(2,value)
OGNL对index方式访问属性做了扩展,它不仅仅可以用整数下标,也可以使用任意的对象做index。OGNL将匹配java对象中下列形式的方法:
public PropertyType getPropertyName(IndexType index)
public void setPropertyName(IndexType index, PropertyType value)
PropertyType 和 IndexType必须在相应的set和get方法中匹配。在webwork中的Session对象就有:
public Object getAttribute(String name)
public void setAttribute(String name, Object value)
来设置任意类型的属性值。使用OGNL表达式来访问就是:
session.attribute[“foo”]
三、Collections伪属性(Pseudo-Properties)
Collections中有很多特殊的属性可以通过OGNL来访问,Collections并不遵循javabeans的命名规则,像size()、length()等等。罗列如下
Collection
Special Properties
Collection (inherited by Map, List & Set)
size
The size of the collection
isEmpty
Evaluates to true if the collection is empty
List
iterator
Evalutes to an Iterator over the List.
Map
keys
Evalutes to a Set of all keys in the Map.
values
Evaluates to a Collection of all values in the Map.
Note:
These properties, plus size and isEmpty, are different than the indexed form of access for Maps (i.e. someMap["size"] gets the "size" key from the map, whereas someMap.size gets the size of the Map.
Set
iterator
Evalutes to an Iterator over the Set.
Iterator
next
Evalutes to the next object from the Iterator.
hasNext
Evaluates to true if there is a next object available from the Iterator.
Enumeration
next
Evalutes to the next object from the Enumeration.
hasNext
Evaluates to true if there is a next object available from the Enumeration.
nextElement
Synonym for next.
hasMoreElements
Synonym for hasNext.