序:在之前这篇《Struts2数据传输的背后机制:ValueStack(值栈)(转载)》博文中指出ognl对于struts2的使用在于
因此本文的重点在于ognl标签是如何在jsp,struts2配置文件中进行使用的,ognl表达式是如何使用的?作为%,$,#三个表达式使用符号,我们分别来介绍这三种的应用
场景。
有#和无#的使用,直接贴源码:
Action源码:
public class OgnlAction {
private String actionStr;
private OgnlBean ob;
private List ognlList;
private Map ognlMap;
public String execute() {
/*---------------------Action属性-------------------------*/
this.setActionStr("ac");
OgnlBean ob = new OgnlBean();
ob.setBeanStr("ob");
this.setOb(ob);
ognlList=(List) new ArrayList<Object>();
ognlList.add("1");
ognlList.add("2");
this.setOgnlList(ognlList);
ognlMap=new HashMap<String, Object>();
ognlMap.put("1", 1);
ognlMap.put("2", 2);
this.setOgnlMap(ognlMap);
/*---------------------ActionContext.getContext()属性-------------------------*/
HttpServletRequest hreq=ServletActionContext.getRequest();
HttpSession session=hreq.getSession();
ServletContext aplication=ServletActionContext.getServletContext();
hreq.setAttribute("actionStr", actionStr);
session.setAttribute("ob", ob);
aplication.setAttribute("ognlList", ognlList);
return "success";
}
public String getActionStr() {
return actionStr;
}
....get,set省略
}
JSP源码: <body>
<table border="1">
<tr >
<td colspan="2" align="center">Action属性获取</td>
</tr>
<tr>
<td>普通属性</td>
<td><s:property value="actionStr"/></td>
</tr>
<tr>
<td>Bean属性</td>
<td><s:property value="ob.beanStr"/></td>
</tr>
<tr>
<td>List属性</td>
<td>
<s:property value="ognlList[0]"/> :
<s:property value="ognlList.size"/>
</td>
</tr>
<tr>
<td>Map属性</td>
<td>
<s:property value="ognlMap.keys.toArray()[1]"/>:
<s:property value="ognlMap.values.toArray()[1]"/>
</td>
</tr>
<tr>
<td>
Action方法(普通public)
</td>
<td>
<s:property value="getActionStr()"/>
</td>
</tr>
<tr>
<td colspan="2">其他诸如静态方法的调用,选择查询等不常用,有需要百度。</td>
</tr>
<tr>
<td colspan="2" align="center">ActionContext属性获取 #</td>
</tr>
<tr>
<td>request属性</td>
<td>
<s:property value="#request.actionStr"/>
</td>
</tr>
<tr>
<td>session属性</td>
<td>
<s:property value="#session.ob.beanStr"/>
</td>
</tr>
<tr>
<td>ServletContext属性</td>
<td>
<s:property value="#application.ognlList[0]"/>
</td>
</tr>
</table>
</body>
ps:
1.值栈(ValueStack) :
可以在值栈中放入、删除、查询对象。访问值栈中的对象不用“#”。Struts2总是把当前Action实例放置在栈顶。所以在OGNL中引用Action中的属性也可以省略“#”。2.调用ActionContext的put(key,value)放入的数据,需要使用#访问。3.#符号的用途一般有三种。— 访问非根对象属性,例如#session.msg表达式,由于Struts 2中值栈被视为根对象,所以访问其他非根对象时,需要加#前缀。实际上,#相当于ActionContext. getContext();#session.msg表达式相当于ActionContext.getContext().getSession(). getAttribute("msg") 。
— 用于过滤和投影(projecting)集合,如persons.{?#this.age>25},persons.{?#this.name=='pla1'}.{age}[0]。
— 用来构造Map,例如示例中的#{'foo1':'bar1', 'foo2':'bar2'}。
注:ps部分都摘自网络。
$符号主要有两个方面的用途。
— 在国际化资源文件中,引用OGNL表达式,例如国际化资源文件中的代码:reg.agerange=国际化资源信息:年龄必须在${min}同${max}之间。
— 在Struts 2框架的配置文件中引用OGNL表达式,例如:
%符号的用途是在标志的属性为字符串类型时,计算OGNL表达式的值