Working with OGNL you can reference action context objects like #application
, #session
,#root
, #action
,#request
,#parameters
,#attr
, and the action context with #context
.
The framework sets the OGNL context to be our ActionContext, and the value stack to be the OGNL root object.
And OGNL uses []
as index reference to access an object properties. For example if the object foo
has a property bar
then it can access like foo.bar
or foo['bar']
. It also works if foo
is a map and bar
is a key.
Now, I want to put a variable and a value to the value stack context like that
<s:set var="bar" value="'hello'"/>
<s:set var="foo" value="'bar'"/>
and print the value
<s:property value="%{#attr[#foo]}"/>
It should print hello
.
I'd like to know how this works. I know that #attr
is an object that doesn't have a property referenced by #foo
, i.e. bar
. However this works. It also works if I use #request
and #context
, and probably #root
instead of #attr
. Neither of this objects has a property bar
, but OGNL thinks otherwise. I'd like to know what OGNL thinks about property of the object it references and why this expression is working. Also if there are alternative ways to print hello
using #foo
reference in OGNL expression.
In the given expression
<s:property value="#attr[#foo]"/>
the part inside[]
will be evaluated first. The#foo
is resolved tobar
so expression becomes#attr['bar']
(which is equivalent to#attr.bar
).Using
#attr.bar
the value forbar
will be searched until it is found in the page context, then in therequest
, then in thesession
and then in theapplication
scope.The
#context.bar
gets value from OGNL context value map with keybar
.The
#request.bar
tries to get request attribute with namebar
from the request map and if it isn't found thenbar
will be searched in the value stack. This happens in Struts2 request wrapper implementation.