Struts2与OGNL

来源:互联网 发布:单片机使用教程 编辑:程序博客网 时间:2024/05/21 05:57

Struts2默认的表达式语言是OGNL。

相关概念:

(1)Struts2与OGNL的关系:(来自Struts2文档)

The framework sets the OGNL context to be our ActionContext, and the value stack to be the OGNL root object. (The value stack is a set of several objects, but to OGNL it appears to be a single object.) Along with the value stack, the framework places other objects in the ActionContext, including Maps representing the application, session, and request contexts. These objects coexist in the ActionContext, alongside the value stack (our OGNL root).

                     |                     |--application                     |                     |--session       context map---|                     |--value stack(root)                     |                     |--action (the current action)                     |                     |--request                     |                     |--parameters                     |                     |--attr (searches page, request, session, then application scopes)                     |

(2)访问value stack中的对象:

值栈是ognl上下文中的根对象,可直接访问。对于值栈中的对象访问,Struts2提供了特殊的OGNLPropertyAccessor

可以自动查找栈内的所有对象(从栈顶到栈底),也就是说,访问值栈中的任何对象都不需要使用“#”标记。


如果两个对象obj1和obj2具有相同的属性name,obj1先入栈,位于栈底(相对),obj2后入栈,位于栈顶,当使用表达式name属性名获取值时,获取到的是obj2的name值,就是说,访问值栈中的对象的属性或方法,无需显示指明对象和“#”标记,就像值栈中的对象都是ognl上下文的根对象一样,这就是

struts2对ognl做出的改进。



具体例子:

使用ognl处理Collections(Maps,Lists,Sets):

(1)构建Map语法:#{key1:value1,key2:value2}。

<s:select label="label" name="name" list="#{'foo':'foovalue', 'bar':'barvalue'}" />

(2)构建List语法:{e1,e2,e3}. 下面例子中name2作为默认值。

<s:select label="label" name="name" list="{'name1','name2','name3'}" value="%{'name2'}" />

(3)访问静态成员:

(4)value stack中的Action实例:

Action实例总是被放在value stack的栈顶,value stack又是ognl中的根对象。所以访问Action示例的属性无需使用"#"标记,但是访问ActionContext中的其他对象时(命名对象),必须使用"#"告诉ognl不要在根对象中查找。

(5)Struts2中的命名对象:

Struts2还提供了一些命名对象,保存在ActionContext中非value stack区域,访问时需要使用#标记(见4),这些命名对象都以map形式存在:

parameters:用于访问请求参数

如:#parameters['id']或#parameters.id,相当于调用了HttpServletRequest对象的getParameter()方法。

request  :用于访问请求属性。

如:#request['user']或#request.user,相当于调用了HttpServletRequest对象的getAttribute()方法。

session :用于访问session属性。

如:#session['user']或#session.user,相当于调用了HttpSession对象的getAttribute()方法。

application :用于访问application属性。

如:#application['user']或#application.user,相当于调用了ServletContext的getAttribute()方法

attr  : 如果PageContext可用,则访问PageContext,否则依次搜索request、session和application对象。


未完待续......