OGNL(Object Graph Navigation Language),是一種表達式語言。使用這種表達式語言,你可以通過某種表達式語法,存取Java對象樹中的任意屬性、調用Java對象樹的方法、同時能夠自動實現必要的類型轉化。如果我們把表達式看做是一個帶有語義的字符串,那么OGNL無疑成為了這個語義字符串與Java對象之間溝通的橋梁。既然OGNL那么強大,那么讓我們一起來研究一下他的API,看看如何使用OGNL.
OGNL的API看起來就是兩個簡單的靜態方法:
- public static Object getValue( Object tree, Map context, Object root ) throws OgnlException;
- public static void setValue( Object tree, Map context, Object root, Object value ) throws OgnlException
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上下文和Action上下文,#相當於ActionContext.getContext();下表有幾個ActionContext中有用的屬性:
-
名稱
作用
例子
parameters
包含當前HTTP 請求參數的Map
#parameters.id[0] 作用相當於 request.getParameter("id")
request
包含當前 HttpServletRequest 的屬性 (attribute)的Map
#request.userName相當於 request.getAttribute("userName")
session
包含當前 HttpSession的 屬性(attribute) 的Map
#session.userName相當於 session.getAttribute("userName")
application
包含當前應用的 ServletContext 的屬性(attribute) 的Map
#application.userName相當於 application.getAttribute("userName")
attr
用於按request > session > application 順序訪問其屬性 (attribute)
#attr.userName相當於 按順序在以上三個范圍(scope) 內讀取userName屬性,直到找到為止
-
用於過濾和投影(projecting)集合,如books.{?#this.price<100};
-
構造Map,如#{'foo1':'bar1', 'foo2':'bar2'}。
"%“符號
%符號的用途是在標志的屬性為字符串類型時,計算OGNL表達式的值,這個類似js中的eval,很暴力。
"$"符號
$符號主要有兩個方面的用途。
— 在國際化資源文件中,引用OGNL表達式,例如國際化資源文件中的代碼:reg.agerange=國際化資源信息:年齡必須在${min}同${max}之間。
— 在Struts 2框架的配置文件中引用OGNL表達式,例如:
<action name="AddPhoto" class="addPhoto"> <interceptor-ref name="fileUploadStack" /> <result type="redirect">ListPhotos.action?albumId=${albumId}</result> </action>
下面代碼實例對OGNL有更深的了解:
Cat.java
package com.oumyye.struts2.ognl; public class Cat { private Dog friend; public Dog getFriend() { return friend; } public void setFriend(Dog friend) { this.friend = friend; } public String miaomiao() { return "miaomiao"; } }
Dog.java
package com.oumyye.struts2.ognl; public class Dog { private String name; public Dog() { } public Dog(String name) { super(); this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "dog: " + name; } }
User.java
package com.oumyye.struts2.ognl; public class User { private int age = 8; public User() { } public User(int age) { super(); this.age = age; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "user" + age; } }
OgnlAction.java
package com.oumyye.struts2.ognl; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import com.opensymphony.xwork2.ActionSupport; public class OgnlAction extends ActionSupport { private Cat cat; private Map<String, Dog> dogMap = new HashMap<String, Dog>(); private Set<Dog> dogs = new HashSet<Dog>(); private String password; private User user; private String username; private List<User> users = new ArrayList<User>(); public OgnlAction() { users.add(new User(1)); users.add(new User(2)); users.add(new User(3)); dogs.add(new Dog("dog1")); dogs.add(new Dog("dog2")); dogs.add(new Dog("dog3")); dogMap.put("dog100", new Dog("dog100")); dogMap.put("dog101", new Dog("dog101")); dogMap.put("dog102", new Dog("dog102")); } public String execute() { return SUCCESS; } public Cat getCat() { return cat; } public Map<String, Dog> getDogMap() { return dogMap; } public Set<Dog> getDogs() { return dogs; } public String getPassword() { return password; } public User getUser() { return user; } public String getUsername() { return username; } public List<User> getUsers() { return users; } public String m() { return "hello"; } public void setCat(Cat cat) { this.cat = cat; } public void setDogMap(Map<String, Dog> dogMap) { this.dogMap = dogMap; } public void setDogs(Set<Dog> dogs) { this.dogs = dogs; } public void setPassword(String password) { this.password = password; } public void setUser(User user) { this.user = user; } public void setUsername(String username) { this.username = username; } public void setUsers(List<User> users) { this.users = users; } }
ognl.jsp
<?xml version="1.0" encoding="UTF-8" ?> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="/struts-tags" prefix="s" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>OGNL表達式語言學習</title> </head> <body> <ol> <li>訪問值棧中的action的普通屬性: username = <s:property value="username"/> </li> <li>訪問值棧中對象的普通屬性(get set方法):<s:property value="user.age"/> | <s:property value="user['age']"/> | <s:property value="user[\"age\"]"/> | wrong: <%--<s:property value="user[age]"/>--%></li> <li>訪問值棧中對象的普通屬性(get set方法): <s:property value="cat.friend.name"/></li> <li>訪問值棧中對象的普通方法:<s:property value="password.length()"/></li> <li>訪問值棧中對象的普通方法:<s:property value="cat.miaomiao()" /></li> <li>訪問值棧中action的普通方法:<s:property value="m()" /></li> <hr /> <li>訪問靜態方法:<s:property value="@com.oumyye.struts2.ognl.S@s()"/></li> <li>訪問靜態屬性:<s:property value="@com.oumyye.struts2.ognl.S@STR"/></li> <li>訪問Math類的靜態方法:<s:property value="@@max(2,3)" /></li> <hr /> <li>訪問普通類的構造方法:<s:property value="new com.oumyye.struts2.ognl.User(8)"/></li> <hr /> <li>訪問List:<s:property value="users"/></li> <li>訪問List中某個元素:<s:property value="users[1]"/></li> <li>訪問List中元素某個屬性的集合:<s:property value="users.{age}"/></li> <li>訪問List中元素某個屬性的集合中的特定值:<s:property value="users.{age}[0]"/> | <s:property value="users[0].age"/></li> <li>訪問Set:<s:property value="dogs"/></li> <li>訪問Set中某個元素:<s:property value="dogs[1]"/></li> <li>訪問Map:<s:property value="dogMap"/></li> <li>訪問Map中某個元素:<s:property value="dogMap.dog101"/> | <s:property value="dogMap['dog101']"/> | <s:property value="dogMap[\"dog101\"]"/></li> <li>訪問Map中所有的key:<s:property value="dogMap.keys"/></li> <li>訪問Map中所有的value:<s:property value="dogMap.values"/></li> <li>訪問容器的大小:<s:property value="dogMap.size()"/> | <s:property value="users.size"/> </li> <hr /> <li>投影(過濾):<s:property value="users.{?#this.age==1}[0]"/></li> <li>投影:<s:property value="users.{^#this.age>1}.{age}"/></li> <li>投影:<s:property value="users.{$#this.age>1}.{age}"/></li> <li>投影:<s:property value="users.{$#this.age>1}.{age} == null"/></li> <hr /> <li>[]:<s:property value="[0].username"/></li> </ol> <s:debug></s:debug> </body> </html>
index.jsp
<?xml version="1.0" encoding="GB18030" ?> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <% String contextPath = request.getContextPath(); %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Insert title here</title> </head> <body> 訪問屬性 <a href="<%=contextPath %>/ognl.action?username=u&password=p">ognl</a> </body> </html>
Struts.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <constant name="struts.enable.DynamicMethodInvocation" value="false" /> <constant name="struts.ognl.allowStaticMethodAccess" value="true"></constant> <package name="ognl" extends="struts-default"> <action name="ognl" class="com.oumyye.struts2.ognl.OgnlAction"> <result>/ognl.jsp</result> </action> <action name="test" class="com.oumyye.struts2.ognl.TestAction"> <result type="chain">ognl</result> </action> </package> </struts>
結果如下