Search code examples
listjspstruts2iteratorognl

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


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?


Solution

  • 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