Struts2 iterator tag - access specific object value from list of objects

蹲街弑〆低调 提交于 2019-12-12 07:21:21

问题


Is there a way to access an attribute of specific object from list of objects.

I've a List of Labs and each Lab object has multiple attributes. Using tag, can we access value of attribute1 of Lab1 object from the list of labs?

Let's say: one of my Lab object has an attribute called labname with value "BP" and another lab object has labname of "A1c".
Now, if I want to access the labvalue attribute of lab object with labname as "BP" how do I achieve it?


回答1:


If you don't want to use a Map, that's easier, then you can exploit the OGNL's List Selection feature:

Selecting From Collections

OGNL provides a simple way to use an expression to choose some elements from a collection and save the results in a new collection. We call this "selection," from the database term for choosing a subset of rows from a table. For example, this expression:

listeners.{? #this instanceof ActionListener}

returns a list of all those listeners that are instances of the ActionListener class.

[...]

Then in the case you described, if you want to filter only the element of the list with the labname attribute equals to "BP" it would be:

<span>
    labvalue attribute for the (first, if any) laboratory with labname="BP" is : 
    <s:property value="labsList.{^ #this.labname == 'BP' }[0].labvalue" />
</span>

with no need of iterators at all.

You can also iterate a projected / selected list, btw ;)

<span>
    All labvalue attributes for all the laboratories with labname="BP" are : 
    <s:iterator value="labsList.{? #this.labname == 'BP' }" >
        <s:property value="labvalue" />
    </s:iterator>
</span>

Enjoy




回答2:


Hope this will help

Give the list to the value attribute in s:iterator Define the object name in the var attribute

<s:iterator value="labsList" status="mbrindex" var="lab">
<s:property value="%{#lab.id}" />


来源:https://stackoverflow.com/questions/23664009/struts2-iterator-tag-access-specific-object-value-from-list-of-objects

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