I can't believe how something this simple can seem so hard to do in Struts 2.
This is approximately what I would like to do as it would be done in Java.
for (Parent parent : parents){
for (Child child: parent.getChildren()){
System.out.println(child.getName());
}
}
That should translate to something close to this in Stuts tags:
<s:iterator var="parent" value="parents">
<s:iterator var="child" value="parent.children">
<s:property value="child.name"/>
<s:iterator>
<s:iterator>
I assume parent.children should be something like ${%(#parent.children)} but I have not found a right combination of ${%(# characters to use :-). I could also use a link to a page explaining when to use which one of these.
Try this:
<s:iterator var="parent" value="parents">
<s:iterator var="child" value="#parent.children">
<s:property value="#child.name"/>
<s:iterator>
<s:iterator>
It works for me:
<s:iterator value="parents">
<s:iterator value="children">
<s:property value="name" />
</s:iterator>
</s:iterator>
This is how the JSP code will look like:
<s:form action="saveaction" >
<s:iterator value="lstBean" id="lstBean" status="outerStat">
<s:textfield value="%{name}" name="lstBean[%{#outerStat.index}].name"/>
<s:textfield value="%{amt}" name="lstBean[%{#outerStat.index}].amt"/>
<s:textfield value="%{id}" name="lstBean[%{#outerStat.index}].id"/>
<s:iterator value="%{lstString}" status="myStat">
<s:textfield name="lstBean[%{#outerStat.index}].lstString[%{#myStat.index}]"/>
</s:iterator>
</s:iterator>
<s:submit value="Click me to submit lstBean"/>
</s:form>
Following is the bean(XBean) whose List is used in the JSP:
public class XBean
{
private ArrayList<String> lstString=new ArrayList<String>();
private String name;
private Double amt;
private Integer id;
//Getters and setters of fields
}
Now you can simply have a field lstBean with setters in your submitting action (saveaction) and hey you are done.
For Struts 2.3.x you can use this example, extracted from http://struts.apache.org/release/2.3.x/docs/iterator-tag-examples.html
In this example, 'countries' is a list of country objects, each of which has a name and a list of cities. Each city has a name.
<s:iterator value="countries">
<s:iterator value="cities">
<s:property value="name"/>, <s:property value="[1].name"/><br>
</s:iterator>
</s:iterator>
They refer to a specific position on the stack: '[1]'. The top of the stack, position 0, contains the current city, pushed on by the inner iterator; position 1 contains the current country, pushed there by the outer iterator.
来源:https://stackoverflow.com/questions/2327466/struts-2-nesting-iterators