Saturday, 11 February 2012

Struts2 - Nested Iterators


Hey Googler,
Unable to find out a more versatile solution of having a nested iterator in Struts2. Want to know the naming convention to be used in JSP, in case of nested iterator so that it can be submitted through a form ?Here comes the solution.

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!!!!

Download an example project. (Netbeans 6.9 project)

No comments:

Post a Comment