Iterate through a List property of an object with Struts2

1.1k Views Asked by At

Considering the following:

public class Company {
    private String name;
    private List<Person> employees;

    //getters and setters
}

public class Person {
    private String name;
    private List<Car> cars;

    //getters and setters
}

public class Car {
    private String color;

    //getter and setter
}

I want to get with Struts2 the color property of every car for every employee. So how would I iterate over the list of cars of every employee of the Company object?

After creating it, I put employees as employeeList into session. Using the following method, I can only get the name property, but can't iterate over the cars property:

<s:if test="#session.employeeList.size() > 0">
    <s:iterator value="#session.employeeList">
        <s:property value="name" /> //this works
        <s:property value="cars" /> //how do I iterate over this list?
    </s:iterator>
</s:if>

Doing this, the output for "cars" property is ognl.NoConversionPossible

I tried something like:

<s:if test="#session.employeeList.size() > 0">
    <s:iterator value="#session.employeeList">
        <s:property value="name" /> //this works
        <s:iterator value="cars">
            <s:property value="color" />
        </s:iterator>
    </s:iterator>
</s:if>

but doesn't work that way. Any ideas?

LE: Solution: Actually the iteration works. The objects I was talking about are mapped as Hibernate Entities. The "List cars" property is in fact a @ManyToMany relationship. So, after looking deeper into the error logs I found out that the cars property that I was trying to iterate was not being populated because Hibernate was lazily initializing it by default. I changed the FetchType to EAGER and the problem was solved.

1

There are 1 best solutions below

1
On

The fact that I use session over the action attributes is not really important. Though, how could I use action attributes in this case? It doesn't seem doable.

Why not ?

Action:

public class MyAction extends ActionSupport {
    private Company company;         // private attribute
    public Company getCompany(){     // public getter
        return company; 
    }

    public String execute(){
        company = someService.loadTheCompanySomehow();
        return SUCCESS;
    }
}

JSP:

<s:iterator value="company.employees">
    <s:property value="name" />
    <s:iterator value="cars">
        <s:property value="color" />
    </s:iterator>
</s:iterator>

If the inner iteration doesn't work, there is probably something you have not shown to us, or related to the way you've cleaned the code before posting it.