Accessing current item properties in a Struts2 iterator

Often you can experience some troubles accessing correctly the objects (and their properties) on which you’re iterating through a iterator tag.

Let’s consider this action that simply returns an Item list obtained from our business service.

 
public class MyAction extends ActionSupport {
  private List myList;
  private MyService myService;

  public String myMethod() {
    myList = myService.getItemList();
    return ActionSupport.SUCCESS;
 }
  public List getMyList() {
    return myList;
  }
}

The MyItem bean class:

 
public class MyItem {
  private String name;
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
}

In the jsp we iterate on myList (that results in the execution of getMyList() in the action) and we try to display the name property of each item (defined in the id attribute of the iterator tag) that calls the getName() method of the Item bean.

These are the results:

 
 
 Doesn't work 
 Works 
 Doesn't work 
 Works 
 Doesn't work 
 Works 
 Works 
 

I hope this little test can be useful.