1 OGNL中符號介紹
1.1 #符號
#
符號的用途一般有三種:
1.1.1 訪問OGNL上下文和Action上下文
訪問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
屬性,直到找到為止
1.1.2 過濾和投影集合
過濾和投影(projecting
)集合,如示例中的persons.{?#this.age>20}
1.1.3 構造map
用來構造Map
,例如示例中的#{’foo1′:’bar1′, ’foo2′:’bar2′}
1.2 %符號
%
符號的用途是在標志的屬性為字符串類型時,轉換為計算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']}” />
1.3 $符號
$
符號主要有兩個方面的用途
1.3.1 引用OGNL
在國際化資源文件中,引用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>
1.3.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
(值棧)中取Action
的(成員屬性)的值。注意這個成員屬性必需存在
注:此處的${}
不是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";
}
}
1.4 @符號
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>
// 兩個@符號
1.5 小結
struts2各個符號總結
$
用於i18n
和Struts
配置文件#
取得ActionContext
的值%
將原本的文本屬性解析為ognl
,對於本來就是ognl
的屬性不起作用@
用於靜態方法或屬性的調用