How to use OGNL index reference operator

2019-02-27 17:57发布

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.

1条回答
三岁会撩人
2楼-- · 2019-02-27 18:07

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.

查看更多
登录 后发表回答