Struts2 Iterating through a List of List

This is a simple example demonstrating how to use the iterator tag in struts2 to iterate through a list of objects which contains another list of objects.
Assume that we have a class called City which contains a list of phone numbers:

public class City {
	private String name;
	private List<PhoneNumber> phoneNumbers;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public List<PhoneNumber> getPhoneNumbers() {
		return phoneNumbers;
	}

	public void setPhoneNumbers(List<PhoneNumber> phoneNumbers) {
		this.phoneNumbers = phoneNumbers;
	}
}


So every city can have many phone numbers. Inside the PhoneNumber class we have

public class PhoneNumber {

	private String prefix;
	private double rate;

	public String getPrefix() {
		return prefix;
	}

	public void setPrefix(String prefix) {
		this.prefix = prefix;
	}

	public double getRate() {
		return rate;
	}

	public void setRate(double rate) {
		this.rate = rate;
	}

}

lets assume that we have an action that returns a list of all cities available. Something like the following:

public class AllRatesAction extends ActionSupport {
	private static final long serialVersionUID = 1L;
	private List<City> allCities;

	//This is the List of cities passed to the JSP page
	public List<City> getAllCities() {
		return allCities;
	}

	public void setAllCities(List<City> allCities) {
		this.allCities = allCities;
	}

	public String execute() {
		//the content of what is happening inside getAllCallRates
		// is not related to this tutrial
		setAllCities(CallRatesDS.getAllCallRates());
		return SUCCESS;
	}

}

The following is how the iterator tags should be used to access the list of City objects and how to access the list of phone numbers inside every city. As you can see we basically create an object of every list and access them through the newly created objects.

<table>
<s:iterator value="allCities" id="cities">
	<s:iterator value="#city.phoneNumbers" id="number">
	<tr>
		<td>
		<!-- Accessing the city name through the city variable -->
			<s:property value="#city.name" />
		</td>
		<td>
			<!-- Accessing the objects inside the phone number object through the number variable -->
			<s:property value="#number.prefix" />
		</td>
		<td>
			<s:property value="#number.rate" />
		</td>
	</tr>
	</s:iterator>
</s:iterator>
</table>

Leave a Reply

Anti-Spam Protection by WP-SpamFree