Struts2 tags seem to evaluate inconsistently

让人想犯罪 __ 提交于 2019-12-02 06:30:30

问题


I have an issue with some Struts2 tags mixed with OGNL. To overcome the fact that you cannot nest evaluation of expressions in OGNL, e.g., %{foo[%{bar}]}, I use successive assignment to variables to get the results that I need.

In the following code, the var grpIndex evaluates correctly, e.g., '6' or '7' in my case, and prints out correctly on the next line. The following statement (line 3) also evaluates correctly, e.g., 'stage' or 'prod' in my case.

However, in the fourth line I try setting that same expression into a variable, using the same syntax as the previous line, so that I can use it in a title. To test this assignment, I try to print out the var on the next line. I would expect the last line to print the same value as the third line. However, this expression prints out nothing. Why is this?

<s:set var="grpIndex" value="%{options[#optstatus.index]}"/>
grpIndex = <s:property value="#grpIndex"/><br/>
grpName = <s:text name="model[%{grpIndex}].groupName"/><br/>
<s:set var="grpName" value="model[%{grpIndex}]).groupName"/>
groupName = <s:property value="#grpName"/>

回答1:


First of all you are using <s:text> (line 3) instead of <s:property> which will yield a wrong test results. Second there is a typo in line 4 (unopened bracket). And most important don't use %{} inside [] in <s:property> or <s:set> tags.

<s:set var="grpIndex" value="options[#optstatus.index]"/>
grpIndex = <s:property value="#grpIndex"/><br/>
grpName = <s:property value="model[#grpIndex].groupName"/><br/>
<s:set var="grpName" value="model[#grpIndex].groupName"/>
groupName = <s:property value="#grpName"/>



回答2:


First, you are not completely correct saying that you cannot nest evaluation of expressions in OGNL. If you look at the Expression Evaluation of the OGNL Language Gude, you will find that if you use parenthesized expression without a dot in front of the parentheses the result of evaluating that expression will be used as expression to be evaluated. See the example here.

Second, I don't see the reason for which you are getting indexes other than iterator index.

Third, the set tag places variables to the value stack context that is accessible via # notation. See the examples here.

Fourth, answering your direct question:

Because a typo in the fourth line. Replace the line with

<s:set var="grpName" value="model[%{#grpIndex}].groupName"/>

will do what expected. You can see the differences in expression.

The last is just reference to show you where you should use %{} to force evaluation of expression, because Struts is parsing everything (by default) in the tag attributes for OGNL.

The usage of %{} notation:

Used in OGNL to force evaluate the content in brackets as OGNL expression.



来源:https://stackoverflow.com/questions/22970016/struts2-tags-seem-to-evaluate-inconsistently

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!