1. 程式人生 > >EL和OGNL表達式的區分

EL和OGNL表達式的區分

etc ssa copy ram req validator rop tails type

OGNL是通常要結合Struts 2的標誌一起使用,如<s:property value="#xx" /> struts頁面中不能單獨使用,el可以單獨使用 ${sessionScope.username}

頁面取值區別:

名稱

servlet

ognl el

parameters

request.getParameter("username")

#username ${username}

request

request.getAttribute("userName")

#request.userName ${requestScope.username}

session

session.getAttribute("userName")

#session.userName ${sessionScope.username}

application

application.getAttribute("userName")

#application.userName ${applicationScope.username}

attr

用於按request > session > application順序訪問其屬性(attribute)

#attr.userName相當於按順序在以上三個範圍(scope)內讀取userName屬性,直到找到為

2.ognl講解

OGNL是Struts 2默認的表達式語言。是Object Graphic Navigation Language(對象圖導航語言)的縮寫,它是一個開源項目。

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表達式的值。如下面的代碼所示:
構造Map

[html] view plain copy print ?
  1. <s:set name=”foobar” value=”#{’foo1′:’bar1′, ‘foo2′:’bar2′}” />
  2. <p>The value of key “foo1″ is <s:property value=”#foobar[‘foo1‘]” /></p>
  3. <p>不使用%:<s:url value=”#foobar[‘foo1‘]” /></p>
  4. <p>使用%:<s:url value=”%{#foobar[‘foo1‘]}” /></p>

The value of key "foo1" is bar1

不使用%:#foobar[‘foo1‘]

使用%:bar1

3.$符號

$符號主要有兩個方面的用途。
在國際化資源文件中,引用OGNL表達式,例如國際化資源文件中的代碼:reg.agerange=國際化資源信息:年齡必須在${min}同${max}之間。
在Struts 2框架的配置文件中引用OGNL表達式,例如下面的代碼片斷所示:

[html] view plain copy print ?
    1. <validators>
    2. <field name=”intb”>
    3. <field-validator type=”int”>
    4. <param name=”min”>10</param>
    5. <param name=”max”>100</param>
    6. <message>BAction-test校驗:數字必須為${min}為${max}之間!</message>
    7. </field-validator>
    8. </field>
    9. </validators>

--------理解二

兩者都是在服務器端執行的,JSP轉化為servlet並編譯為java文件,其中會把EL,OGNL,<% %>等解釋出來,並返回給客戶端。

OGNL表達式依賴於struts2標簽,必須結合struts2標簽使用,如:<s:property value="#student.name"></s:property>

但是<a href="checkInfo.jsp?id=%{#student.studentid}">查看信息</a>這樣是不行的,因為<a>標簽不是struts2標簽

當然可以把它改為<s:a href="checkInfo.jsp?id=%{#student.studentid}">查看信息</s:a>這樣就行.

說明:<s:a href="checkInfo.jsp?id=%{#student.studentid}">中%{ }作用是告訴解釋器,這之間的代碼為OGNL表達式,這很有用。

EL表達式形式為${內容},如${sessionScope.user.name}. 不能用在java表達式<% %>之內,因為兩者是兩種不同的表達式。

EL表達式不能用在struts2標簽裏。

EL表達式能用在內部文件的js裏(jsp被解釋時,內部文件的js代碼也被解釋,然後發送到客戶端,而外部js文件是在客戶端執行的,所以EL表達式不能用在外部js文件裏)

如:alert("${sessionScope.user.name}"), 加上雙引號或單引號。

說明:js文件裏不能使用OGNL表達式(因為它只能結合struts2標簽使用)

EL和OGNL表達式的區分