OGNL表達式基本語法與用法詳解
一.OGNL中的#、%和$符號
#、%和$符號在OGNL表達式中經(jīng)常出現(xiàn),而這三種符號也是開發(fā)者不容易掌握和理解的部分。在這里我們簡單介紹它們的相應用途。
1.#符號的三種用法
1)訪問非根對象屬性,例如示例中的#session.msg表達式,由于Struts 2中值棧被視為根對象,所以訪問其他非根對象時,需要加#前綴。實際上,#相當于ActionContext. getContext();#session.msg表達式相當于ActionContext.getContext().getSession(). getAttribute("msg") 。
2)用于過濾和投影(projecting)集合,如示例中的persons.{?#this.age>20}。
3) 用來構造Map,例如示例中的#{'foo1':'bar1', 'foo2':'bar2'}。
2.%符號
%符號的用途是在標志的屬性為字符串類型時,計算OGNL表達式的值。如下面的代碼所示:
<h3>構造Map</h3>
<s:set name="foobar" value="#{'foo1':'bar1', 'foo2':'bar2'}" />
<p>The value of key "foo1" is <s:property value="#foobar['foo1']" /></p>
<p>不使用%:<s:url value="#foobar['foo1']" /></p>
<p>使用%:<s:url value="%{#foobar['foo1']}" /></p>
運行界面如下所示。
he value of key "foo1" is bar1 不使用%:#foobar['foo1'] 使用%:bar1
3.$符號
$符號主要有兩個方面的用途。
1) 在國際化資源文件中,引用OGNL表達式,例如國際化資源文件中的代碼:reg.agerange=國際化資源信息:年齡必須在
${min}同${max}之間。
2) 在Struts 2框架的配置文件中引用OGNL表達式,例如下面的代碼片斷所示:
<validators>
<field name="intb">
<field-validator type="int">
<param name="min">10</param>
<param name="max">100</param>
<message>BAction-test校驗:數(shù)字必須為${min}為${max}之間!</message>
</field-validator>
</field>
</validators>
二.我們一起看一下OGNL常用表達式:
1. 當使用OGNL調(diào)用靜態(tài)方法的時候,需要按照如下語法編寫表達式:
@package.classname@methodname(parameter)
2. 對于OGNL來說,java.lang.Math是其的默認類,如果調(diào)用java.lang.Math的靜態(tài)方法時,無需指定類的名字,比如:@@min(4, 10);
3. 對于OGNL來說,數(shù)組與集合是一樣的,都是通過下標索引來去訪問的。
獲取List:<s:property value="testList"/><br>
獲取List中的某一個元素(可以使用類似于數(shù)組中的下標獲取List中的內(nèi)容):<s:property value="testList[0]"/><br>
獲取Set:<s:property value="testSet"/><br>
獲取Set中的某一個元素(Set由于沒有順序,所以不能使用下標獲取數(shù)據(jù)):<s:property value="testSet[0]"/><br> ×
獲取Map:<s:property value="testMap"/><br>
獲取Map中所有的鍵:<s:property value="testMap.keys"/><br>
獲取Map中所有的值:<s:property value="testMap.values"/><br>
獲取Map中的某一個元素(可以使用類似于數(shù)組中的下標獲取List中的內(nèi)容):
<s:property value="testMap['m1']"/><br>
獲取List的大小:<s:property value="testSet.size"/><br>
4. 使用OGNL來處理映射(Map)的語法格式如下所示:
#{‘key1': ‘value1', ‘key2': ‘value2', ‘key3': ‘value3'};
5. 過濾(filtering):collection.{? expression}
6. OGNL針對集合提供了一些偽屬性(如size,isEmpty),讓我們可以通過屬性的方式來調(diào)用方法(本質原因在于集合當中的很多方法并不符合JavaBean的命名規(guī)則),但我么你依然還可以通過調(diào)用方法來實現(xiàn)與偽屬性相同的目的。
7. 過濾(filtering),獲取到集合中的第一個元素:collection.{^ expression}
8. 過濾(filtering),獲取到集合中的最后一個元素:collection.{& expression}
9. 在使用過濾操作時,我們通常都會使用#this,該表達式用于代表當前正在迭代的集合中的對象(聯(lián)想增強的for循環(huán))
10. 投影(projection):collection.{expression}
11. 過濾與投影之間的差別:類比于數(shù)據(jù)庫中的表,過濾是取行的操作,而投影是取列的操作。 具體舉例如下:
利用選擇獲取List中成績及格的對象:<s:property value="stus.{?#this.grade>=60}"/><br>
利用選擇獲取List中成績及格的對象的username:
<s:property value="stus.{?#this.grade>=60}.{username}"/><br>
利用選擇獲取List中成績及格的第一個對象的username:
<s:property value="stus.{?#this.grade>=60}.{username}[0]"/><br>
利用選擇獲取List中成績及格的第一個對象的username:
<s:property value="stus.{^#this.grade>=60}.{username}"/><br>
利用選擇獲取List中成績及格的最后一個對象的username:
<s:property value="stus.{$#this.grade>=60}.{username}"/><br>
利用選擇獲取List中成績及格的第一個對象然后求大小:
<s:property value="stus.{^#this.grade>=600}.{username}.size"/><br>
12. 在Struts2中,根對象就是ValueStack。在Struts2的任何流程當中,ValueStack中的最頂層對象一定是Action對象。
13. parameters,#parameters.username
request, #request.username
session, #session.username
application, #application.username
attr, #attr.username
以上幾個對象叫做“命名對象”。
14. 訪問靜態(tài)方法或是靜態(tài)成員變量的改進。
@vs@method
15. 關于Struts2標簽庫屬性值的%與#號的關系:
1). 如果標簽的屬性值是OGNL表達式,那么無需加上%{}。
2). 如果標簽的屬性值是字符串類型,那么在字符串當中凡是出現(xiàn)的%{}都會被解析成OGNL表達式,解析完畢后再與其他的字符串進行拼接構造出最后的字符串值。
3). 我們可以在所有的屬性值上加%{},這樣如果該屬性值是OGNL表達式,那么標簽處理類就會將%{}忽略掉。
最后一起用代碼說話,簡單的看一下ognl操作的示例:
1)上下文環(huán)境中使用OGNL
public static void main(String[] args)
{
Map<String , Object> context = new HashMap<String , Object>();
Person person1 = new Person();
person1.setName("zhangsan");
Person person2 = new Person();
person2.setName("lisi");
Person person3 = new Person();
person3.setName("wangwu");
Person person4 = new Person();
person4.setName("zhaoliu");
context.put("person1", person1);
context.put("person2", person2);
context.put("person3", person3);
try
{
Object value = Ognl.getValue("name", context, person2);
System.out.println("ognl expression \"name\" evaluation is : " + value);
Object value2 = Ognl.getValue("#person2.name", context, person2);
System.out.println("ognl expression \"#person2.name\" evaluation is : " + value2);
Object value3 = Ognl.getValue("#person1.name", context, person2);
System.out.println("ognl expression \"#person1.name\" evaluation is : " + value3);
Object value4 = Ognl.getValue("name", context, person4);
System.out.println("ognl expression \"name\" evaluation is : " + value4);
Object value5 = Ognl.getValue("#person4.name", context, person4);
System.out.println("ognl expression \"person4.name\" evaluation is : " + value5);
// Object value6 = Ognl.getValue("#person4.name", context, person2);
// System.out.println("ognl expression \"#person4.name\" evaluation is : " + value6);
}
2)使用OGNL調(diào)用方法
public static void main(String[] args)
{
OgnlContext context = new OgnlContext();
People people1 = new People();
people1.setName("zhangsan");
People people2 = new People();
people2.setName("lisi");
People people3 = new People();
people3.setName("wangwu");
context.put("people1", people1);
context.put("people2", people2);
context.put("people3", people3);
context.setRoot(people1);
try
{
Object value = Ognl.getValue("name.length()", context, context.getRoot());
System.out.println("people1 name length is :" + value);
Object upperCase = Ognl.getValue("#people2.name.toUpperCase()", context, context.getRoot());
System.out.println("people2 name upperCase is :" + upperCase);
Object invokeWithArgs = Ognl.getValue("name.charAt(5)", context, context.getRoot());
System.out.println("people1 name.charAt(5) is :" + invokeWithArgs);
Object min = Ognl.getValue("@java.lang.Math@min(4,10)", context, context.getRoot());
System.out.println("min(4,10) is :" + min);
Object e = Ognl.getValue("@java.lang.Math@E", context, context.getRoot());
System.out.println("E is :" + e);
}
3)使用OGNL操作集合
public static void main(String[] args) throws Exception
{
OgnlContext context = new OgnlContext();
Classroom classroom = new Classroom();
classroom.getStudents().add("zhangsan");
classroom.getStudents().add("lisi");
classroom.getStudents().add("wangwu");
classroom.getStudents().add("zhaoliu");
classroom.getStudents().add("qianqi");
Student student = new Student();
student.getContactWays().put("homeNumber", "110");
student.getContactWays().put("companyNumber", "119");
student.getContactWays().put("mobilePhone", "112");
context.put("classroom", classroom);
context.put("student", student);
context.setRoot(classroom);
Object collection = Ognl.getValue("students", context, context.getRoot());
System.out.println("students collection is :" + collection);
Object firstStudent = Ognl.getValue("students[0]", context, context.getRoot());
System.out.println("first student is : " + firstStudent);
Object size = Ognl.getValue("students.size()", context, context.getRoot());
System.out.println("students collection size is :" + size);
System.out.println("--------------------------飄逸的分割線--------------------------");
Object mapCollection = Ognl.getValue("#student.contactWays", context, context.getRoot());
System.out.println("mapCollection is :" + mapCollection);
Object firstElement = Ognl.getValue("#student.contactWays['homeNumber']", context, context.getRoot());
System.out.println("the first element of contactWays is :" + firstElement);
System.out.println("--------------------------飄逸的分割線--------------------------");
Object createCollection = Ognl.getValue("{'aa','bb','cc','dd'}", context, context.getRoot());
System.out.println(createCollection);
Object createMapCollection = Ognl.getValue("#{'key1':'value1','key2':'value2'}", context, context.getRoot());
System.out.println(createMapCollection);
}
}
總結
以上就是本文關于OGNL表達式基本語法與用法詳解的全部內(nèi)容,希望對大家有所幫助,有問題的話可以隨時留言,小編會及時回復大家的。感興趣的朋友可以繼續(xù)參閱:Struts2 通過ognl表達式實現(xiàn)投影 、 Struts2 OGNL表達式實例詳解等。
相關文章
淺談SpringMVC之視圖解析器(ViewResolver)
本篇文章主要介紹了淺談SpringMVC之視圖解析器(ViewResolver),具有一定的參考價值,有興趣的可以了解一下2017-08-08
簡單解析java方法在調(diào)用在內(nèi)存中的執(zhí)行過程
這篇文章主要介紹了簡單解析java方法在調(diào)用在內(nèi)存中的執(zhí)行過程,文章圍繞主題展開詳細的內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下2022-07-07
詳解SpringBoot中@NotNull,@NotBlank注解使用
這篇文章主要為大家詳細介紹了Spring?Boot中集成Validation與@NotNull,@NotBlank等注解的簡單使用,感興趣的小伙伴可以跟隨小編一起學習一下2022-08-08

