概况
OGNL就是Object Graph Navigation Language的缩写(对象图形导航语言) - 可以从 http://www.ognl.org 获取OGNL的完整文档. 这篇文档中我们只演示与Webwork共存的一部分OGNL功能的例子. 如果想回顾基本的概念, 请参考 OGNL基础.
Webwork使用了标准的上下文命名来进行OGNL表达式求值. OGNL处理的顶级对象是一个map (一般以context map(上下文map)引用). OGNL有 一个根对象的概念 (在webwork中, 它就是OGNLValueStack). 顺着根对象, 其它对象被放置在context map中 (作为上下文引用), 包括你的 session/application/request/attr 这些map. 这些对象与根对象无关, 它们只是存在于context map的一边 (保存在context map中). 所以, 访问这些对象时需要使用 # 来告诉ongl不要在根对象中寻找, 而是在其它的上下文中进行寻找.
|--request
|
|--application
|
context map---|--OgnlValueStack(root)
|
|--session
|
|--attr
|
|--parameters
注意context map中还有其它的对象, 我们在这个例子中只引用了一部分. 现在, 你的action中的实例已经被保存在OGNLValueStack中, 你可不用写 # 就可以引用这些bean属性了.
<ww: property value="myBean.myProperty"/>
对于 sessions,request,或者context map中的其它上下文:
ActionContext.getContext().getSession().put("mySessionPropKey", mySessionObject);
<ww:property value="#session.mySessionPropKey"/> or
<ww:property value="#session['mySessionPropKey']"/> or
<ww:property value="#attr.mySessionPropKey"/>
集合Collections (Maps, Lists, Sets)
在webwork中经常要处理集合类 (map, list, 和set), 所以这里有一些使用select标签的例子:
list的语法: {e1,e2,e3}. 这样会创建一个包含String "name1", "name2" and "name3" 的List. 它还选择了 "name2" 作为默认值. 注意 Alt Syntax 的使用提供了字面意义 (literal) 上的 "name2".
map的语法: #{key1:value1,key2:value2}. 这样会创建一个map, 它将string "foo"影射到 string "foovalue", 将string "bar"影射到string "barvalue":
<ww:select label="label" name="name" list="#{'foo':'foovalue', 'bar':'barvalue'}" />
You may need to determine if an element exists in a collection. You can accomplish this with the operations in and not in
你可能需要确定一个元素是否存在于一个集合中. 你可以通过 in 和 not in 操作来实现.
<ww:if test="'foo' in {'foo','bar'}">
muhahaha
</ww:if>
<ww:else>
boo
</ww:else>
<ww:if test="'foo' not in {'foo','bar'}">
muhahaha
</ww:if>
<ww:else>
boo
</ww:else>
选择 (select) 一个集合的子集 (叫做投影), 你可以在collection中使用通配符.
- ? - 所有符合选择逻辑的元素
- ^ - 符合选择逻辑的第一个元素
- $ - 符合选择逻辑的最后一个一个元素
选择一个person (人) 对象的所有male relatives (男性亲属) 的子集:
person.relatives.{? #this.gender == 'male'}
Lambda表达式 (Lambda Expressions)
OGNL支持基本的lambda表达式语法, 允许你写一些简单的函数. 例如:
对于你们这些数学系的人,以为永远也不会再看到这个的人们.
Fibonacci(斐波那契序列): if n==0 return 0; elseif n==1 return 1; else return fib(n-2)+fib(n-1);
fib(0) = 0
fib(1) = 1
fib(11) = 89
有用的信息 lambda表达式就是括号中那部分. 这个 #this 变量代表这个表达式的参数, 它的初始值为11. |
<ww:property value="#fib =:[#this==0 ? 0 : #this==1 ? 1 : #fib(#this-2)+#fib(#this-1)], #fib(11)" />