OGNL(Object-Graph Navigation Language)全稱物件圖導航語言,是一種功能強大的表達式語言。它透過簡潔語法實現:物件屬性存取、方法呼叫、物件圖遍歷、型別轉換等功能,是 Struts 2 預設的表達式引擎。
Map(ognl.OgnlContext),含根物件。根物件屬性可直接存取,非根物件需加 #key 前綴。<s:property value="xxx"/>)均透過 OGNL 存取 ActionContext 資料。ActionContext 設為 OGNL 上下文,值棧作為根物件放入其中。#;當前 Action 實例常駐棧頂,屬性可直接引用。put(key, value) 放入的資料,存取時必須加 #。# 符號:三大用途#session.msg ≡ ActionContext.getContext().getSession().getAttribute("msg")persons.{? #this.age > 25}、persons.{? #this.name == 'pla1'}.{age}[0]#{ 'foo1':'bar1', 'foo2':'bar2' }% 符號:強制求值當標籤屬性為字串時,% 強制將內容作為 OGNL 表達式求值,類似 JS eval()。
$ 符號:配置與國際化引用reg.agerange=年齡必須在 ${min} 到 ${max} 之間<message>數字必須為 ${min} 到 ${max} 之間!</message>public class OGNL1 {
public static void main(String[] args) {
Person person = new Person();
person.setName("zhangsan");
try {
Object value = Ognl.getValue("name", person);
System.out.println(value); // 輸出: zhangsan
} catch (OgnlException e) {
e.printStackTrace();
}
}
}
class Person {
private String name;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
}
Ognl.getValue(expression, root) 結合解析與求值,從根物件提取屬性值。
初學者應重點掌握:值棧與根物件關係、# 與非根物件存取、集合操作語法。建議搭配 Struts 2 標籤庫實作練習,體會 OGNL 在表單綁定、資料顯示、驗證訊息中的實際應用場景。