一.#符號的用途一般有三種。
“#”主要有三種用途:
1. 訪問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屬性,直到找到為止
2)用於過濾和投影(projecting)集合,如示例中的persons.{?#this.age>20}。
3)用來構造Map,例如示例中的#{’foo1′:’bar1′, ’foo2′:’bar2′}。
二.%符號
%符號的用途是在標志的屬性為字符串類型時,轉換為計算OGNL表達式的值。如下面的代碼所示:
構造Map
<s:set name=”foobar” value=”#{’foo1′:’bar1′, ‘foo2′:’bar2′}” />
The value of key “foo1″ is <s:property value=”#foobar['foo1']” />
不使用%:<s:url value=”#foobar['foo1']” />
使用%:<s:url value=”%{#foobar['foo1']}” />
三.$符號
$符號主要有兩個方面的用途。
在國際化資源文件中,引用OGNL表達式,例如國際化資源文件中的代碼:reg.agerange=國際化資源信息:年齡必須在${min}同${max}之間。
在Struts 2框架的配置文件中引用OGNL表達式,例如下面的代碼片斷所示:
<validators>
<field name=”intb”>
<field-validator type=”int”>
<param name=”min”>10</param>
<param name=”max”>100</param>
<message>BAction-test校驗:數字必須為${min}為${max}之間!</message>
</field-validator>
</field>
</validators>
2、動態的結果集(dynamic result)
<struts>
<constant name="struts.devMode" value="true" />
<package name="user" namespace="/user" extends="struts-default">
<action name="user" class="com.bjsxt.struts2.user.action.UserAction">
<result>${r}</result>
</action>
</package>
</struts>
注:${}:作用是用於在配置文件中從Value stack(值棧)中取值。
例如:${r} 表示從Value stack(值棧)中取rAction的(成員屬性)的值。注意這個成員屬性必需存在
注:此處的${}不是el表達式。
get/set方法。
Action類中指定了r的值。這樣就動態確定了Result的值
public class UserAction extends ActionSupport {
private int type;
private String r;
public String getR() {
return r;
}
public void setR(String r) {
this.r = r;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
@Override
public String execute() throws Exception {
if(type == 1) r="/user_success.jsp";
else if (type == 2) r="/user_error.jsp";
return "success";
}
}
四、@符號
package com. wjt276.struts2.ognl;
public class S {
public static String STR = "STATIC STRING";
public static String s() {
return "static method";
}
}
<li>訪問靜態方法:<s:property value="@com.wjt276.struts2.ognl.S@s()"/></li>
<li>訪問靜態屬性:<s:property value="@com.wjt276.struts2.ognl.S@STR"/></li>
<li>訪問Math類的靜態方法:<s:property value="@@max(2,3)" /></li> // 兩個@符號
小結:
$ # % @
a) $ 用於i18n和Struts配置文件
b) # 取得ActionContext的值
c) % 將原本的文本屬性解析為ognl,對於本來就是ognl的屬性不起作用
d) @ 用於靜態方法或屬性的調用