Struts 2.0 - getting mutiple datas through model driven

779 views Asked by At

I have jsp page with following details

<s:form>

Enter fname:
Enter lname:

Address1:

Enter City:
Enter Pin:

Address2:

Enter City:
Enter Pin:

Address3:

Enter City:
Enter Pin:

</s:form>

Now i need to fetch all the entries into a single DTO object using the model driven feature.

But how can i get mutiple entries of address fields. The DTO class will contain same for each address fields ie city and pin. Eg: the DTO class will look like :

public class Details {

String fname;
String lname;
String city;
String pin;

public String getFname() {
    return fname;
}
public void setFname(String fname) {
    this.fname = fname;
}
public String getLname() {
    return lname;
}
public void setLname(String lname) {
    this.lname = lname;
}
public String getCity() {
    return city;
}
public void setCity(String city) {
    this.city = city;
}
public String getPin() {
    return pin;
}
public void setPin(String pin) {
    this.pin = pin;
}
}

Or i can get them only if i use

String[] city;
String[] pin;

Also what should of the name of input tag be. Will it be

<input type="text" name="city" /> for all city entries 

or

Is there any other option to get the multiple entries.

1

There are 1 answers

0
Kamil Chaber On

If we suppose that your form looks like this:

public class MyForm {
    private List<Details> addresses;
    private String fname;
    private String lname;

    public List<Details> getAddresses() {
        return this.addresses;
    }

    public void setAddresses(List<Details> addresses) {
        this.addresses = addresses;
    }

    /*

    getters and setters for fname and lname properties;    

    */
}

and your action, which is implementing ModelDriven looks like this:

public class MyAction extends ActionSupport implements ModelDriven<MyForm> {
     private MyForm myForm = new MyForm();

     public String execute() {
          /*

          ....


          */
     }

     @Override
     public MyForm getModel() {
          return this.myform;
     }
}

in your JSP file you can set these values as follow:

<%@ taglib prefix="s" uri="/struts-tags"%>
<s:form action="your_action" method="post">

Enter fname: <s:textfield name="fname"/>
Enter lname: <s:textfield name="lname"/>

Address1:

Enter City: <s:textfield name="addresses[0].city"/>
Enter Pin: <s:textfield name="addresses[0].pin"/>

Address2:

Enter City: <s:textfield name="addresses[1].city"/>
Enter Pin: <s:textfield name="addresses[1].pin"/>

Address3:

Enter City: <s:textfield name="addresses[2].city"/>
Enter Pin: <s:textfield name="addresses[2].pin"/>

</s:form>