首先了解下OGNL的概念:
OGNL是Object-Graph Navigation Language的縮寫,全稱為對象圖導航語言,是一種功能強大的表達式語言,它通過簡單一致的語法,可以任意存取對象的屬性或者調用對象的方法,能夠遍歷整個對象的結構圖,實現對象屬性類型的轉換等功能。
此外,還得先需弄懂OGNL的一些知識:
1.OGNL表達式的計算是圍繞OGNL上下文進行的。
OGNL上下文實際上就是一個Map對象,由ognl.OgnlContext類表示。它里面可以存放很多個JavaBean對象。它有一個上下文根對象。
上下文中的根對象可以直接使用名來訪問或直接使用它的屬性名訪問它的屬性值。否則要加前綴“#key”。
2.Struts2的標簽庫都是使用OGNL表達式來訪問ActionContext中的對象數據的。如:<s:propertyvalue="xxx"/>。
3.Struts2將ActionContext設置為OGNL上下文,并將值棧作為OGNL的根對象放置到ActionContext中。
4.值棧(ValueStack) :
可以在值棧中放入、刪除、查詢對象。訪問值棧中的對象不用“#”。
Struts2總是把當前Action實例放置在棧頂。所以在OGNL中引用Action中的屬性也可以省略“#”。
5.調用ActionContext的put(key,value)放入的數據,需要使用#訪問。
OGNL中重要的3個符號:#、%、$:
#、%和$符號在OGNL表達式中經常出現,而這三種符號也是開發者不容易掌握和理解的部分,需要時間的積累才漸漸弄清楚……
1.#符號
#符號的用途一般有三種。
訪問非根對象屬性,例如#session.msg表達式,由于Struts 2中值棧被視為根對象,所以訪問其他非根對象時,需要加#前綴。實際上,#相當于ActionContext. getContext();#session.msg表達式相當于ActionContext.getContext().getSession(). getAttribute("msg") 。
用于過濾和投影(projecting)集合,如persons.{?#this.age>25},persons.{?#this.name=='pla1'}.{age}[0]。
用來構造Map,例如示例中的#{'foo1':'bar1', 'foo2':'bar2'}。
2.%符號
%符號的用途是在標志的屬性為字符串類型時,計算OGNL表達式的值,這個類似js中的eval,很暴力。
3.$符號
$符號主要有兩個方面的用途。
在國際化資源文件中,引用OGNL表達式,例如國際化資源文件中的代碼:reg.agerange=國際化資源信息:年齡必須在${min}同${max}之間。
在Struts 2框架的配置文件中引用OGNL表達式,例如:
1
2
3
4
5
6
7
8
9
|
<validators> <field name="intb"> <field-validator type="int"> <param name="min">10</param> <param name="max">100</param> <message>BAction-test校驗:數字必須為${min}為${max}之間!</message> </field-validator> </field> </validators> |
示例:第一個OGNL程序
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
public class OGNL1 { public static void main(String[] args) { /* 創建一個Person對象 */ Person person = new Person(); person.setName("zhangsan"); try { /* 從person對象中獲取name屬性的值 */ Object value = Ognl.getValue( "name" , person); System.out.println(value); } catch (OgnlException e) { e.printStackTrace(); } } } class Person { private String name; public String getName() { return name; } public void setName(String name) { this .name = name; } } |
控制臺輸出:
1
|
zhangsan |
可以看到我們正確的取得了person對象的name屬性值,該getValue聲明如下:
1
2
3
4
5
6
7
8
9
|
public static <T> T getValue(String expression,Object root)throws OgnlException Convenience method that combines calls to parseExpression and getValue. Parameters: expression - the OGNL expression to be parsed root - the root object for the OGNL expression Returns: the result of evaluating the expression |
OGNL會根據表達式從根對象(root)中提取值。