Skip to content Skip to sidebar Skip to footer

Struts 2 - Pattern/strategy For Multiple Objects On The Same Page

I'm looking for a good design pattern/strategy for how to using the Struts 2 framework for editing multiple objects of the same type on an HTML page. Struts is really good for edi

Solution 1:

The strategy here is to use a Map<Integer, Address>.

Example Bean Class

Let's assume the following example Address class.

publicclassAddress{
  privateString line1;
  privateString line2;
  privateString city;
  privateString state;
  privateString zipCode;

  // getters and setters here
}

Example Action

publicclassExampleActionextendsActionSupport{
  /**
   * A map of ID -> Address.
   */private Map<Integer, Address> addresses = Maps.newLinkedHashMap();

  // ... action method(s) and validate herepublic Map<Integer, Address> getAddresses() {
    return addresses;
  }
}

In your JSP layer, you can iterate over the map (each iteration is a Map.Entry) and output the fields (line1, line2, city, etc.) for each. The field names should be:

addresses[0].line1
addresses[0].line2
addresses[0].city
addresses[0].state
addresses[0].zipCode

...

addresses[5].line1
addresses[5].line2
addresses[5].city
addresses[5].state
addresses[5].zipCode

To perform validation, just iterate over the map and check each field appropriately. When editing addresses, you can use the primary key of the address from your database. For adding new addresses, you can just increment starting from zero. The index can be any number, so long as its unique within the map.

Solution 2:

I typically map out everything I need to use in a form and group them into related classes, Person, Address, Misc for example. I will then create a wrapper class and use delegate accessor methods to provide a single interface to access the individual objects. Most often I work with JPA entites so these classes are already set up for me, I just need the wrapper and maybe some utility methods for CRUD functions. For example:

publicclassContactWrapperimplementsSerializable{
    privatePerson person;
    privateAddress address;
    privateMisc misc;

    // Getters / Setters for primary objects - person, address, misc
    ...
    // Delegate accessorspublicStringgetName(){
        return person.getName();
    }

    publicStringsetName(String name){
        return person.setName(name);
    }
    ...
}

Now you have one object to work with in your action class and jsp's which can be references however you choose.

In your action class:

publicclassContactActionextendsActionSupport{
    private ContactWrapper contact;
    ....
}

In your JSP:

<s:textfieldname="contact.name" />

Struts handles all the object instantiation auto-magically, even in objects contained inside other objects.

Post a Comment for "Struts 2 - Pattern/strategy For Multiple Objects On The Same Page"