什么是OGNL
表達式語言主要有以下幾大好處:
- 避免(MyType) request.getAttribute()和myBean.getMyProperty()之類的語句,使頁面更簡潔;
- 支持運算符(如+-*/),比普通的標志具有更高的自由度和更強的功能;
- 簡單明了地表達代碼邏輯,使用代碼更可讀與便於維護。
OGNL如何融入框架
數據進入,當請求進入框架時,它作為一個HttpServletRequest對象公開給java語言,像我們之前知道的Struts建立在servlet api上,請求參數被作為名、值對存儲,名字和值都是string類型。接下來框架開始出來來源這些請求參數的的數據的轉移及類型的轉換。OGNL自動將數據轉移到ValueStack的對象上,我們把user對象作為動作組件javabean屬性公開出來,將動作對象放到valuestack上,我們已經准備好讓OGNL做導航型的工作。
從攔截器的學習知道,param攔截器將會把請求的數據轉移到valuestack上,這個工作微妙的地方就是將參數映射到valuestack上的一個真實屬性,從圖中國可以看出,你期望表達式會更像myAction.user.name,而實際只有user.name是必要的。
Struts 2中的表達式語言
Struts 2支持以下幾種表達式語言:
- OGNL(Object-Graph Navigation Language),可以方便地操作對象屬性的開源表達式語言;
- JSTL(JSP Standard Tag Library),JSP 2.0集成的標准的表達式語言;
- Groovy,基於Java平台的動態語言,它具有時下比較流行的動態語言(如Python、Ruby和Smarttalk等)的一些起特性;
- Velocity,嚴格來說不是表達式語言,它是一種基於Java的模板匹配引擎,具說其性能要比JSP好。
Struts 2默認的表達式語言是OGNL,原因是它相對其它表達式語言具有下面幾大優勢:
- 支持對象方法調用,如xxx.doSomeSpecial();
- 支持類靜態的方法調用和值訪問,表達式的格式為@[類全名(包括包路徑)]@[方法名 | 值名],例如:@java.lang.String@format('foo %s', 'bar')或@tutorial.MyConstant@APP_NAME;
- 支持賦值操作和表達式串聯,如price=100, discount=0.8, calculatePrice(),這個表達式會返回80;
- 訪問OGNL上下文(OGNL context)和ActionContext;
- 操作集合對象。
OGNL的用法
大家經常遇到的問題是#、%和$這三個符號的使用。下面我想通過例子講述這個問題:
首先新建名為Struts2_OGNL的Web工程,配置開發環境。之前很多朋友在使用Struts 2的過程中都遇到亂碼問題。當然亂碼問題由來已久,而且涉及多方面的知識,所以並非三言兩語可以說明白,而且互聯網上也已經有很多這方便的文章,大家可以 Google一下。不過,如果你在開發的過程,多注意一下,避免亂碼問題也不難。亂碼多數是由於編碼與解碼所使用的方式不同造成的,所以我建議大家將編碼 方式都設為“utf-8”,如<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" %>。另外,在配置web.xml時使用ActionContextCleanUp過濾器(Filter),如下面代碼所示:
< web-app id ="WebApp_9" version ="2.4"
xmlns ="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation ="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" >
< display-name > Struts 2 OGNL </ display-name >
< filter >
< filter-name > struts-cleanup </ filter-name >
< filter-class >
org.apache.struts2.dispatcher.ActionContextCleanUp
</ filter-class >
</ filter >
< filter-mapping >
< filter-name > struts-cleanup </ filter-name >
< url-pattern > /* </ url-pattern >
</ filter-mapping >
< filter >
< filter-name > struts2 </ filter-name >
< filter-class >
org.apache.struts2.dispatcher.FilterDispatcher
</ filter-class >
</ filter >
< filter-mapping >
< filter-name > struts2 </ filter-name >
< url-pattern > /* </ url-pattern >
</ filter-mapping >
< welcome-file-list >
< welcome-file > index.html </ welcome-file >
</ welcome-file-list >
</ web-app >
清單1 WebContent/WEB-INF/web.xml
“#”主要有三種用途:
- 訪問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'}。
下面讓我們它們的具體寫法,首先是Action類代碼:


























































清單2 src/tutorial/action/OgnlAction.java
以上代碼分別在request、session和application的范圍內添加“userName”屬性,然后再在JSP頁面使用OGNL將 其取回。我還創建了Book對象的列表用於演示“用於過濾和投影(projecting)集合”的功能,至於Book的代碼大家可以在我前一文章《在Struts 2中實現CRUD》看到。
下面是Ognl.jsp的代碼,內容如下:
<% @ taglib prefix = " s " uri = " /struts-tags " %>
<! 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 >
< title > Struts OGNL Demo </ title >
</ head >
< body >
< h3 > 訪問OGNL上下文和Action上下文 </ h3 >
< p > parameters: < s:property value ="#parameters.userName" /></ p >
< p > request.userName: < s:property value ="#request.userName" /></ p >
< p > session.userName: < s:property value ="#session.userName" /></ p >
< p > application.userName: < s:property value ="#application.userName" /></ p >
< p > attr.userName: < s:property value ="#attr.userName" /></ p >
< hr />
< h3 > 用於過濾和投影(projecting)集合 </ h3 >
< p > Books more than $35 </ p >
< ul >
< s:iterator value ="books.{?#this.price > 35}" >
< li >< s:property value ="title" /> - $ < s:property value ="price" /></ li >
</ s:iterator >
</ ul >
< p > The price of "Code Complete, Second Edition" is: < s:property value ="books.{?#this.title=='Code Complete, Second Edition'}.{price}[0]" /></ p >
< hr />
< 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 >
</ body >
</ html >
清單3 WebContent/Ognl.jsp
以上代碼值得注意的是“<s:property value="books.{?#this.title=='Code Complete, Second Edition'}.{price}[0]"/>”,因為“books.{?#this.title=='Code Complete, Second Edition'}.{price}”返回的值是集合類型,所以要用“[索引]”來訪問其值。
最后是Struts 2的配置文件struts.xml,內容如下:
<! 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.devMode" value ="true" />
< package name ="Struts2_OGNL_DEMO" extends ="struts-default" >
< action name ="Ognl" class ="tutorial.action.OgnlAction" >
< result > /Ognl.jsp </ result >
</ action >
</ package >
</ struts >
清單4 src/struts.xml
發布運行應用程序,結果如下所示:
“%”符號的用途是在標志的屬性為字符串類型時,計算OGNL表達式的值。例如在Ognl.jsp中加入以下代碼:
< h3 > %的用途 </ h3 >
< p >< s:url value ="#foobar['foo1']" /></ p >
< p >< s:url value ="%{#foobar['foo1']}" /></ p >
清單6 演示%用途的代碼片段
刷新頁面,結果如下所示:
清單7 示例運行結果2
“$”有兩個主要的用途
用於在國際化資源文件中,引用OGNL表達式。
在Struts 2配置文件中,引用OGNL表達式,如
< interceptor-ref name ="fileUploadStack" />
< result type ="redirect" > ListPhotos.action?albumId=${albumId} </ result >
</ action >
清單8 演示$用途的代碼片段
總結
OGNL是一種功能很大的表達式語言,熟悉它可以使我們的開發變得更快捷。
本文部分內容轉自http://www.blogjava.net/max/archive/2007/04/28/114417.html MAX ON JAVA