1

使用 OGNL,您可以引用动作上下文对象,如#application, #session, #root, #action, #request, #parameters,#attr和动作上下文#context

该框架将 OGNL 上下文设置为我们的 ActionContext,并将值堆栈设置为 OGNL 根对象。

OGNL[]用作索引引用来访问对象属性。例如,如果对象foo有一个属性bar,那么它可以访问 likefoo.barfoo['bar']。如果foo是地图并且bar是键,它也可以工作。

现在,我想像这样将一个变量和一个值放入值堆栈上下文中

<s:set var="bar" value="'hello'"/>
<s:set var="foo" value="'bar'"/>

并打印值

<s:property value="%{#attr[#foo]}"/>

它应该打印hello

我想知道这是如何工作的。我知道这#attr是一个没有 引用的属性的对象#foo,即bar。然而,这有效。如果我使用#requestand#context并且可能#root代替. 它也可以工作#attr。这两个对象都没有属性bar,但 OGNL 不这么认为。我想知道 OGNL 对它引用的对象的属性有什么看法,以及为什么这个表达式有效。此外,如果有其他方法可以在 OGNL 表达式中hello使用引用进行打印。#foo

4

1 回答 1

2

In the given expression <s:property value="#attr[#foo]"/> the part inside [] will be evaluated first. The #foo is resolved to bar so expression becomes #attr['bar'] (which is equivalent to #attr.bar).

Using #attr.bar the value for bar will be searched until it is found in the page context, then in the request, then in the session and then in the application scope.

The #context.bar gets value from OGNL context value map with key bar.

The #request.bar tries to get request attribute with name bar from the request map and if it isn't found then bar will be searched in the value stack. This happens in Struts2 request wrapper implementation.

于 2014-05-29T19:21:02.870 回答