Struts2框架使用標準命名上下文來使用OGNL表達式,OGNL表達式處理的頂層對象是Map(通常被稱為上下文Map或上下文)。OGNL認為在應用上下文中有一個根對象(或默認對象)。即不需要使用任何特殊的標記就能夠獲得根對象中的屬性,如果要獲得其他的對象,則需要使用標記#。
Struts2框架把OGNL context作為我們的ActionContext,并且把值棧(ValueStack)作為OGNL的根對象(ValueStack是多個對象的集合,但是對OGNL來說,它是一個單一的對象)。框架把其他對象和ValueStack一起放到ActionContext中,包括展現(xiàn)application、session和request 上下文的Maps,這些對象同ValueStack一起,共同存在于ActionContext中。
|
|--application
|
|--session
context map---|
|--value stack(root)
|
|--request
|
|--parameters
|
|--attr (searches page, request, session, then application scopes)
|
Action實例總是被放入ValueStack中,因為Action在vs中,并且vs是OGNL的根對象,所以在訪問Action的屬性時可以忽略“ # ”標記。但是,在訪問ActionContext中的其他對象時必須要使用“#”,這樣OGNL才能知道我們想要訪問的是Actioncontext中的其他對象,而不去根對象中查找。
訪問Action中的一個屬性 |
<s:property value="postalCode"/> |
Actioncontext中的其他非根對象屬性,可以用“#”標記來獲得。
<s:property value="#session.mySessionPropKey"/> or
<s:property value="#session['mySessionPropKey']"/> or
<s:property value="#request['myRequestPropKey']"/>
同樣Action可以通過一個靜態(tài)的方法來獲取ActionContext:
Actioncontext.getContext();
ActionContext.getContext().getSession().put("mySessionPropKey", mySessionObject);
Collections (Maps, Lists, Sets)
在框架中會經(jīng)常遇到處理集合 Collections (Maps, Lists, and Sets), 下面列出幾個使用select 標簽處理集合的列子. OGNL documentation 也包括許多列子.
Syntax for list: {e1,e2,e3}. 這個語法創(chuàng)建了一個包含字符串“name1”,“name2”和“name3”的List,并且選擇“name2”作為默認值。
<s:select label="label" name="name" list="{'name1','name2','name3'}" value="%{'name2'}" />
Syntax for map: #{key1:value1,key2:value2}. 這個語法創(chuàng)建了一個Map鍵值對集合,“foo”對應“foovalue”,“bar”對應“barvalue”:
<s:select label="label" name="name" list="#{'foo':'foovalue', 'bar':'barvalue'}" />
判斷一個元素是否存在于一個集合中,使用in 或 not in 操作。
<s:if test="'foo' in {'foo','bar'}">
muhahaha
</s:if>
<s:else>
boo
</s:else>
<s:if test="'foo' not in {'foo','bar'}">
muhahaha
</s:if>
<s:else>
boo
</s:else>
選擇集合的一個子集(也叫投影),可以使用通配符:
例如,獲得人的親屬集合中為男性的一個子集
person.relatives.{? #this.gender == 'male'}
Lambda Expressions
OGNL supports basic lamba expression syntax enabling you to write simple functions.
(Dedicated to all you math majors who didn't think you would ever see this one again.)
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
How the expression works
The lambda expression is everything inside the square brackets. The #this variable holds the argument to the expression, which in the following example is the number 11 (the code after the square-bracketed lamba expression, #fib(11)).
<s:property value="#fib =:[#this==0 ? 0 : #this==1 ? 1 : #fib(#this-2)+#fib(#this-1)], #fib(11)" />