本人是一個EL(Expression Language,以下譯為表達式語言)的支持者。因為我對<% %>寫法極為反感,忘記了在那本書上看到的一句話——“使用標志(Tag)的一個目的就是避免在JSP頁面中出現過多的<%%>的語句,使頁面與后臺代碼分離。”
表達式語言主要有以下幾大好處:
- 避免(MyType) request.getAttribute()和myBean.getMyProperty()之類的語句,使頁面更簡潔;
- 支持運算符(如+-*/),比普通的標志具有更高的自由度和更強的功能;
- 簡單明了地表達代碼邏輯,使用代碼更可讀與便于維護。
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的用法
OGNL是通常要結合Struts 2的標志一起使用,如<s:property value="xx" />等。大家經常遇到的問題是#、%和$這三個符號的使用。下面我想通過例子講述這個問題:
首先新建名為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>
“#”主要有三種用途:
- 訪問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類代碼:






































































以上代碼分別在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>
以上代碼值得注意的是“<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>
發布運行應用程序,結果如下所示:
“%”符號的用途是在標志的屬性為字符串類型時,計算OGNL表達式的值。例如在Ognl.jsp中加入以下代碼:
<h3>%的用途</h3>
<p><s:url value="#foobar['foo1']" /></p>
<p><s:url value="%{#foobar['foo1']}" /></p>
刷新頁面,結果如下所示:
清單7 示例運行結果2
“$”有兩個主要的用途
- 用于在國際化資源文件中,引用OGNL表達式,例子請參考《在Struts 2.0中國際化(i18n)您的應用程序》
- 在Struts 2配置文件中,引用OGNL表達式,如
<action name="AddPhoto" class="addPhoto">清單8 演示$用途的代碼片段
<interceptor-ref name="fileUploadStack" />
<result type="redirect">ListPhotos.action?albumId=${albumId}</result>
</action>
總結
OGNL是一種功能很大的表達式語言,熟悉它可以使我們的開發變得更快捷。