Struts2 Access specific index of list when index is a variable

强颜欢笑 提交于 2021-02-07 20:28:08

问题


I'm having some trouble accessing a specific element of a list when the index is a variable.

When the index is just a number, I have no issues at all displaying what I'm looking for.

<s:property value="#session.userList[1].email" />

That works perfectly, and displays the email found in that element of UserList

However, when I change the index to be a variable, I'm having difficulties finding the proper way to write the ognl statement. I've tried every combination of %# I can think of with no luck.

<s:set var="userIndex" >${param.index}</s:set>
<s:property value="#session.userList[#userIndex].email" />

How exactly should I format my ognl statement?


回答1:


You should format it like in this example:

<s:set var="userIndex" value="%{@java.lang.Integer@valueOf(#parameters.index)}" />
<s:property value="%{#session.userList[#userIndex].email}" />

If you are working with the struts tags better use OGNL for evaluate expressions instead of EL. Force OGNL to evaluate whole expression not a part.

Needed to convert to integer type the value of the variable. String types used for names.




回答2:


YOU CAN ALSO USE

<s:set var="index" value="%{@java.lang.Integer@valueOf(#row.index)}" />

this is set a integer value for index

then you can access specific value of a list

<s:property value="%{yourListObject.get(#index).yourField}" />


来源:https://stackoverflow.com/questions/15882328/struts2-access-specific-index-of-list-when-index-is-a-variable

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