问题
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