OGNL表達式語言介紹 OGNL是Object Graphic Navigation Language(對象圖導航語言)的縮寫, 它是一個開源項目。 Struts2框架使用OGNL作為默認的表達式語言。 OGNL相對其它表達式語言具有下面幾大優勢: 1、支持對象方法調用,如xxx.doSomeSpecial(); 2、支持類靜態的方法調用和值訪問,表達式的格式: @[類全名(包括包路徑)]@[方法名 | 值名],例如: @java.lang.String@format('foo %s', 'bar') 或@tutorial.MyConstant@APP_NAME; 3、支持賦值操作和表達式串聯,如price=100, discount=0.8, calculatePrice(),這個表達式會返回80; 4、訪問OGNL上下文(OGNL context)和ActionContext; 5、操作集合對象。 Ognl 有一個上下文(Context)概念,說白了上下文就是一個MAP結構,它實現 了java.utils.Map的接口. ******************************************************************************************* 理解Struts2中的 ValueStack ValueStack實際是一個接口,在Struts2中利用OGNL時,實際上使用的是實現了該接口的OgnlValueStack類,這個類是Struts2利用OGNL的基礎 ValueStack(值棧): 貫穿整個 Action 的生命周期(每個 Action 類的對象實例都擁有一個 ValueStack 對象). 相當於一個數據的中轉站. 在其中保存當前 Action 對象和其他相關對象. Struts 框架把 ValueStack 對象保存在名為 “struts.valueStack” 的請求屬性中,request中 在 ValueStack 對象的內部有兩個邏輯部分: ObjectStack: Struts 把動作和相關對象壓入 ObjectStack 中--List ContextMap: Struts 把各種各樣的映射關系(一些 Map 類型的對象) 壓入 ContextMap 中 Struts 會把下面這些映射壓入 ContextMap 中 parameters: 該 Map 中包含當前請求的請求參數 request: 該 Map 中包含當前 request 對象中的所有屬性 session: 該 Map 中包含當前 session 對象中的所有屬性 application:該 Map 中包含當前 application 對象中的所有屬性 attr: 該 Map 按如下順序來檢索某個屬性: request, session, application 理解OGNL Context *OgnlValueStack 類包含兩個重要的屬性 一個root和一個context。 * 其中root本質上是一個ArrayList. * 而context 是一個Map(更確切的說是一個OgnlContext對象) *在這個OgnlContext對象(context)中,有一個默認的頂層對象 _root,OGNL訪問context中這個默認頂層對象中的元素時,是不需要#號的,直接通過元素的名稱來進行訪問, *而訪問其他對象時,如 request、session、attr等,則需要#號引用。 注:Struts2將OgnlValueStack的root對象賦值給了OgnlContext 中的_root對象,在OgnlValueStack的root對象中,保存着調用Action的實例,因此,在頁面上通過Struts2標簽訪問Action 的屬性時,就不需要通過#號來引用 總結:ognl Context包含 ObjectStack屬性和ContextMap屬性 當Struts2接受一個請求時,會迅速創建ActionContext,ValueStack,action 。然后把action存放進ValueStack,所以action的實例變量可以被OGNL訪問。 注意: Struts2中,OGNL表達式需要配合Struts標簽才可以使用。如:<s:property value="name"/> 理解ActionContext ActionContext提供了對ognl上下文對象中數據操作的方法. ******************************************************************************************* 演示值棧實例 1.編寫JSP <%@ page language="java" pageEncoding="utf-8" contentType="text/html; charset=utf-8"%> <%@ taglib uri="/struts-tags" prefix="s"%> <html> <head> <title>My JSP 'index.jsp' starting page</title> </head> <body> 測試值棧:<br> <a href="${pageContext.request.contextPath}/ognl/valueStackAction_test.action">test</a><br> 2.編寫Action package cn.itcast.ognl; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.util.ValueStack; @SuppressWarnings("serial") public class ValueStackAction extends ActionSupport { public String test(){ ServletActionContext.getRequest().setAttribute("username", "usename_request"); ServletActionContext.getRequest().setAttribute("psw", "psw_request"); ServletActionContext.getServletContext().setAttribute("username", "usename_application"); ServletActionContext.getServletContext().setAttribute("psw", "psw_application"); ServletActionContext.getContext().getSession().put("username", "usename_session"); ServletActionContext.getContext().getSession().put("psw", "psw_session"); //方法一 ValueStack valueStack=ServletActionContext.getContext().getValueStack(); return "valueStack"; } } 3.設置配置文件 <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN" "http://struts.apache.org/dtds/struts-2.1.7.dtd"> <struts> <package name="ognl" namespace="/ognl" extends="struts-default"> <action name="valueStackAction_*" class="cn.itcast.ognl.ValueStackAction" method="{1}"> <result name="valueStack">/ognl/valueStack.jsp</result> </action> 4.struts.xml配置文件導入 <include file="cn/itcast/ognl/struts_ognl.xml"></include> ************************************************************************************************* OGNL表達式語言(#號的用法) 用法1:訪問OGNL上下文和Action上下文,#相當ActionContext.getContext() 1、 如果訪問其他Context中的對象,由於他們不是根對象,所以在訪問時, 需要添加#前綴。 也可寫為#request[‘userName’]或#session[‘userName’]或#appliction[‘userName’] OGNL表達式語言(#號的用法) Action中代碼: ServletActionContext.getRequest().setAttribute("username", "username_request"); ServletActionContext.getServletContext().setAttribute("username", "username_application"); ServletActionContext.getContext().getSession().put("username", "username_session"); ValueStack valueStack=ServletActionContext.getContext().getValueStack(); valueStack.set("username", "username_valueStack"); Jsp頁面: 使用ognl表達式取值*****************************<br> request:<s:property value="#request.username"/><br> session:<s:property value="#session.username"/><br> application:<s:property value="#application.username"/><br> attr:<s:property value="#attr.username"/><br> valueStack:<s:property value="username"/><br> parameters:<s:property value="#parameters.cid[0]"/><br> 用法1:訪問OGNL上下文和Action上下文,#相當ActionContext.getContext() 2 、OGNL會設定一個根對象(root對象),在Struts2中根對象就是ValueStack (值棧) 。如果要訪問根對象(即ValueStack)中對象的屬性,則可以省略 #命名對象,直接訪問該對象的屬性即可。 Action中代碼: ValueStack valueStack=ServletActionContext.getContext().getValueStack(); valueStack.set("username", "username_valueStack"); Jsp頁面: valueStack:<s:property value="username"/> 深入理解值棧中的 ObjectStack 在OgnlValueStack類里有一個List類型的root變量,他存放了一組對象 處於第一位的對象叫棧頂對象。 通常我們在OGNL表達式里直接寫上屬性的名稱即可訪問root變量里對象的屬性, 搜索順序是從棧頂對象開始尋找,如果棧頂對象不存在該屬性,就會從第二個對象尋找,如果沒有找到就從第三個對象尋找,依次往下訪問,直到找到為止。 Action中代碼: ValueStack valueStack=ServletActionContext.getContext().getValueStack(); //set方法放置對象到map中,map再放入到棧(List集合)上 valueStack.set("student", new Student()); valueStack.set("employee", new Employee()); //直接放置對象到棧(List集合)上 valueStack.getRoot().add(0,new Student()); valueStack.getRoot().add(1,new Employee()); Jsp頁面: name:<s:property value="name"/><br> age::<s:property value="age"/><br> number::<s:property value="number"/><br> salary:<s:property value="salary"/><br> ************************************************************************************ 用法2:集合的投影(過濾) 1、集合的投影(只輸出部分屬性) collectionName.{ expression } <s:iterator value="allList.{name}" var="person"> <s:property/> <br> </s:iterator> 2、集合的過濾 1) 集合的過濾有以下三種方式: a.“?#”:過濾所有符合條件的集合,如:users.{?#this.age > 19}; b.“^#”:過濾第一個符合條件的元素,如:users.{^#this.age > 19}; c.“$#”:過濾最后一個符合條件的元素,如:users.{$#this.age > 19} 。 . 2) this 表示集合中的元素; <s:iterator value="allList.{?#this.age>25}" var="person"> <s:property value="name"/> xxxxxx <s:property value="age"/> <br> </s:iterator> 3、集合的投影和過濾 投影(過濾)操作返回的是一個集合,可以使用索引取得集合中指定的 元素,如:users.{?#this.age > 19}[0] <s:iterator value="allList.{?#this.age>25}.{name}" var="person"> <s:property/><br> </s:iterator> <s:iterator value="allList.{?#this.age>25}[0]" var="person"> <s:property/><br> </s:iterator> ************************************************************************************ 用法3:構造Map,如#{‘foo1’:‘bar1’, ‘foo2’:‘bar2’}。 這種方式常用在給radio或select、checkbox等標簽賦值上 jsp頁面: <s:radio list=“#{‘male’:‘男’,‘female’:‘女’}” name=“sex” label=“性別” /> 運行結果是 <input type="radio" name="sex" id="sexmale" value="male"/>男 <input type="radio" name="sex" id="sexfemale" value="female"/>女 Action中的代碼: Map map=new HashMap(); map.put("male", "男"); map.put("female", "女"); ServletActionContext.getRequest().setAttribute("map", map); jsp頁面: <s:property value="#request.map.male"/><br> <s:property value="#request.map['female']"/><br> 運行結果是 男 女 這種方式常用在給radio或select、checkbox等標簽賦值上 Action中的代碼: Map map=new HashMap(); map.put("male", "男"); map.put("female", "女"); ServletActionContext.getRequest().setAttribute("map", map); jsp頁面: <s:radio list="#request.map" name="sex" label="性別" /> 運行結果是 <input type="radio" name="sex" id="sexfemale" value="female"/>女 <input type=“radio” name=“sex” id=“sexmale” value=“male”>男 *********************************************************************************************** OGNL表達式語言(%用法) “%”符號的用途是在標簽的屬性值被理解為字符串類型時,告訴執行環境%{}里的是OGNL表達式。 形式一: { }中ognl表達式 Action中的代碼: ServletActionContext.getRequest().setAttribute("username", "username_request"); jsp頁面: <s:textfield name="name" label="%{#request.username} "/> 運行結果是 username_request : <input type="text" name="name" value="" id="name"/> 形式二: { }中值用 ’ ’引起來,這是不再是ogle表達式,而是普通的字符串 jsp頁面: <s:textfield name="name" label="%{'foo'}"/> 運行結果是 foo : <input type="text" name="name" value="" id="name"/> *********************************************************************************************** OGNL表達式語言($用法) “$”有兩個主要的用途 * 用於在國際化資源文件中,引用OGNL表達式 * 在Struts 2配置文件中,引用OGNL表達式 在struts2配置文件中引用ognl表達式 ,引用request等作用域中的值 Action中的代碼: ServletActionContext.getRequest().setAttribute("msgxx", "msg_request"); struts.xml文件中 <package name="ognl" namespace="/ognl" extends="struts-default" > <action name="ognlAction_*" class="cn.itcast.ognl.OgnlAction" method="{1}"> <result name="ognl">/ognl/ongl.jsp?msg=${#request.msgxx}</result> </action> </package> jsp頁面: parameters Msg:<s:property value="#parameters.msg[0]"/> 運行結果是 msg_request 在struts2配置文件中引用ognl表達式 ,引用值棧的值 Action中的代碼: valueStack.set("msgxx", "msg_valueStack"); struts.xml文件中 <package name="ognl" namespace="/ognl" extends="struts-default" > <action name="ognlAction_*" class="cn.itcast.ognl.OgnlAction" method="{1}"> <result name="ognl">/ognl/ongl.jsp?msg=${msgxx}</result> </action> </package> jsp頁面: parameters Msg:<s:property value="#parameters.msg[0]"/> 運行結果是 msg_valueStack ******************************************************************************************** 對於集合類型,OGNL表達式可以使用in和not in兩個元素符號。其中,in表達式用來判斷某個元素是否在指定的集合對象中;not in判斷某個元素是否不在指定的集合對象中,如下所示。 in表達式: <s:if test="'foo' in {'foo','bar'}"> 在 </s:if> <s:else> 不在 </s:else> not in表達式: <s:if test="'foo' not in {'foo','bar'}"> 不在 </s:if> <s:else> 在 </s:else> 除了in和not in之外,OGNL還允許使用某個規則獲得集合對象的子集,常用的有以下3個相關操作符。 ?:獲得所有符合邏輯的元素。 ^:獲得符合邏輯的第一個元素。 $:獲得符合邏輯的最后一個元素。 例如代碼: <s:iterator value="books.{?#this.price > 35}"> <s:property value="title" /> - $<s:property value="price" /><br> </s:iterator> 在上面代碼中,直接在集合后緊跟.{}運算符表明用於取出該集合的子集,{}內的表達式用於獲取符合條件的元素,本例的表達式用於獲取集合中價格大於35的書集合。 public class BookAction extends ActionSupport { private List<Book> books; .... @Override public String execute() { books = new LinkedList<Book>(); books.add(new Book("A735619678", "spring", 67)); books.add(new Book("B435555322", "ejb3.0",15)); } } ************************************************************************************************ OGNL原理演示實例 實例1 獲取屬性參數 1.編寫JSP <%@ page language="java" pageEncoding="utf-8"%> <%@ taglib uri="/struts-tags" prefix="s"%> <html> <head> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="description" content="This is my page"> </head> <body> 使用El表達式取值#######################################################################################<br> ${requestScope.username}<br> ${sessionScope.username}<br> ${applicationScope.username}<br> <br> 使用ognl表達式取值#######################################################################################<br> 訪問作用域中內容:<br> <s:property value="#request.username"/><br> <s:property value="#session['username']"/><br> <s:property value="#application.username"/><br> <s:property value="#attr.username"/><br> <s:property value="#parameters.cid[0]"/><br> <s:property value="username"/><br> 深入理解值棧中的 ObjectStack#######################################################################################<br> <s:property value="name"/><br> <s:property value="salary"/><br> <s:property value="number"/><br> <s:property value="age"/><br> 用法3:構造Map,如‘foo1’:‘bar1’, ‘foo2’:‘bar2’。#######################################################################<br> <!-- <input type="radio" name="sex" id="sexmale" value="male"/><label for="sexmale">男</label> --> <s:radio name="sex" list="#{'male':'男','female':'女'}" label="性別"></s:radio> <br> <s:property value="#request.map.male"/><br> <s:property value="#request.map.female"/><br> <br> "%"符號的用途是在標簽的屬性值被理解為字符串類型時,告訴執行環境%{}里的是OGNL表達式#######################################################################<br> <br> <s:textfield name="username" value="%{#request.username}"></s:textfield> <s:textfield name="username" value="%{foo}"></s:textfield> <s:textfield name="username" value="%{'foo'}"></s:textfield> "$"有兩個主要的用途<br> * 用於在國際化資源文件中,引用OGNL表達式<br> * 在Struts 2配置文件中,引用OGNL表達式####################################################################<br> <s:property value="#parameters.msg[0]"/> <s:debug/> </body> </html> 2.編寫Action public class OgnlAction extends ActionSupport { private String name="actionName"; private Integer age=10; public String test(){ ServletActionContext.getRequest().setAttribute("username", "usename_request"); ServletActionContext.getRequest().setAttribute("psw", "psw_request"); ServletActionContext.getServletContext().setAttribute("username", "usename_application"); ServletActionContext.getServletContext().setAttribute("psw", "psw_application"); ServletActionContext.getContext().getSession().put("username", "usename_session"); ServletActionContext.getContext().getSession().put("psw", "psw_session"); //在值棧中放入數據 ValueStack valueStack=ServletActionContext.getContext().getValueStack(); //放置值棧匯中的map集合中,map集合放置list中 valueStack.set("username", "username_valueStack"); //直接放置到list(棧)中 valueStack.getRoot().add(0,new Student()); valueStack.getRoot().add(0,new Employee()); //放置map Map map=new HashMap(); map.put("male","男"); map.put("female","女"); ServletActionContext.getRequest().setAttribute("map", map); return "ognl"; } } 3.編寫配置文件 <action name="ognlAction_*" class="cn.itcast.ognl.OgnlAction" method="{1}"> <result name="ognl">/ognl/ognl.jsp?msg=${username}</result> </action> 4.在struts.xml文件中導入配置文件 實例2 表達式的使用 1.編寫JSP <%@ page language="java" pageEncoding="utf-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <%@ taglib uri="/struts-tags" prefix="s"%> <html> <head> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="description" content="This is my page"> </head> <style type="text/css"> .oddClass{ background-color: red;} .evenClass{ background-color:blue;} </style> <body> ognlTag.jsp<br> -----------------------------------------------------------------------------------------------------------<br> property標簽用於輸出指定值:<br> <s:property/><br> value的值為空,則輸出default屬性指定的值<br> <s:property value="#request.xxxxx" default="defaultValue"/><br> 注:escape=“false”時,hr作為html標簽使用<br> <s:property value="%{'<hr> hr的使用'}" escape="false"/> -----------------------------------------------------------------------------------------------------------<br> <s:set value="#request.username" var="xxxx" scope="request"></s:set> <s:property value="#request.xxxx"/> <br> <s:set value="#request.username" var="xx" scope="page"></s:set> <s:property value="#attr.xx"/> <br> <s:set value="#request.username" var="x"></s:set> <s:property value="#x"/> -----------------------------------------------------------------------------------------------------------<br> push:將對象放入棧頂,不能放入其他范圍,當標簽結束,會從棧頂刪除。了解<br> <s:push value="#request.username"> <s:property/> </s:push> -----------------------------------------------------------------------------------------------------------<br> Action:通過指定命名空間和action名稱,該標簽允許在jsp頁面直接調用Action<br> executeResult true類似於inculde<br> <s:action name="ognlAction_test" namespace="/ognl" executeResult="false"></s:action> -----------------------------------------------------------------------------------------------------------<br> Iterator:標簽用於對集合進行迭代,這里的集合包含List、Set和數組<br> 該標簽沒有使用var 則遍歷的對象放入到了棧頂<br> <s:iterator value="#request.allList"> <s:property value="name" /> ~~~~<s:property value="age" /> <br> </s:iterator> <br> <br> <br> <br> 該標簽使用了var 則遍歷的對象放入到了棧頂,同時還放入到map集合中<br> <s:iterator value="#request.allList" var="person"> <s:property value="name" /> ~~~~<s:property value="age" /> <br> <s:property value="#person.name" /> ~~~~<s:property value="#person.age" /> <br> </s:iterator> <br> <br> <s:iterator value="#request.allList" var="person" begin="2" end="6" step="2"> <s:property value="#person.name" /> ~~~~<s:property value="#person.age" /> <br> </s:iterator> <br> <br> <s:iterator value="#request.allList" var="person" status="st"> <s:property value="#person.name" /> ~~~~<s:property value="#person.age" /> <br> 返回當前迭代了幾個元素:<s:property value="#st.count"/><br> 返回當前迭代元素的索引:<s:property value="#st.index"/><br> 回當前被迭代元素的索引是否是偶數:<s:property value="#st.even"/><br> 回當前被迭代元素的索引是否是奇數:<s:property value="#st.odd"/><br> 返回當前被迭代元素是否是第一個元素:<s:property value="#st.first"/><br> 返返回當前被迭代元素是否是最后一個元素:<s:property value="#st.last"/><br> </s:iterator> 應用<br> <table border="1"> <s:iterator value="#request.allList" var="person" status="st"> <tr class="<s:property value='#st.even?"evenClass":"oddClass"'/>"> <td><s:property value="#person.name"/></td> <td><s:property value="#person.age" /></td> <td> <s:if test="#person.age<24">少年</s:if> <s:elseif test="#person.age<27">中年</s:elseif> <s:else>老年</s:else> </td> </tr> </s:iterator> </table> -----------------------------------------------------------------------------------------------------------<br> url:該標簽用於創建url,可以通過"param"標簽提供request參數<br> 注:s:param與s:property標簽在使用時,不需要就加%{},其他的要加<br> <s:url action="oglnAction_test" namespace="/ognl" var="url"> <s:param name="name" value="%{'張三豐'}"></s:param> <s:param name="age" value="12"></s:param> </s:url> <a href='<s:property value="#url"/>'>test</a> <br> 使用value后綴必須加.action<br> <s:url value="oglnAction_test.action" namespace="/ognl" var="url"> <s:param name="name" value="%{'張三豐'}"></s:param> <s:param name="age" value="12"></s:param> </s:url><br> <s:debug/> <a href='<s:property value="#url"/>'>test</a> -----------------------------------------------------------------------------------------------------------<br> ognl操作集合:<br> <s:property value="#request.allList.size"/> -----------------------------------------------------------------------------------------------------------<br> 使用ognl操作list和數組 <br> <s:iterator value="{1,2,3,4}"> <s:property/> </s:iterator> <br> <s:iterator value="{'s1','s2','s3','s4'}" var="str"> <s:property value="#str"/> </s:iterator> -----------------------------------------------------------------------------------------------------------<br> 使用ognl操作map<br> <s:iterator value="#{'key01':'value01','key02':'value02'}"> <s:property/> </s:iterator> <br><br> 處理map集合時, 'key01':'value01','key02':'value02'; key value<br> <s:iterator value="#{'key01':'value01','key02':'value02'}"> <s:property value="key"/>~~~~~ <s:property value="value"/> </s:iterator> <br> <s:iterator value="#{'key01':'value01','key02':'value02'}" var="map"> <s:debug/> <s:property value="#map.key"/>~~~~~ <s:property value="#map.value"/> </s:iterator> -----------------------------------------------------------------------------------------------------------<br> 集合的投影(只輸出部分屬性)<br> <s:iterator value="#request.allList.{name}" var="person"> <s:property/> <br> </s:iterator> -----------------------------------------------------------------------------------------------------------<br> 集合的過濾<br> <s:iterator value="#request.allList.{?#this.age>24}" var="person"> <s:property value="name"/> ~~ <s:property value="age"/> <br> </s:iterator> -----------------------------------------------------------------------------------------------------------<br> 集合的投影和過濾 <s:iterator value="#request.allList.{?#this.age>24}.{name}" var="person"> <s:property/> <br> </s:iterator> </body> </html> 2.編寫Action public class OgnlTagAction extends ActionSupport { private static final long serialVersionUID = 1L; private List allList; public String test(){ ServletActionContext.getRequest().setAttribute("username", "usename_request"); ServletActionContext.getServletContext().setAttribute("username", "usename_application"); ServletActionContext.getContext().getSession().put("username", "usename_session"); //在值棧中放入數據 ValueStack valueStack=ServletActionContext.getContext().getValueStack(); //放置值棧匯中的map集合中,map集合放置list中 //valueStack.set("username", "username_valueStack"); allList=new ArrayList(); //初始化集合 for(int i=0;i<10;i++){ Person p=new Person("tom"+i,20+i); allList.add(p); } ServletActionContext.getRequest().setAttribute("allList", allList); return "ognlTag"; } } 3.設置配置文件 <action name="ognlTagAction_*" class="cn.itcast.ognl.OgnlTagAction" method="{1}"> <result name="ognlTag">/ognl/ognlTag.jsp</result> </action> 4.導入到Struts.xml文件中
原文:http://blog.sina.com.cn/s/blog_3eb047df0100pyls.html
