views:

23

answers:

1

Hi all,

I have a class Account

public class Account {
private int id;
private String name;
//getters and setters
}

and a class Contact

private class Contact {
private int contactid;
private Account account;
//getters and setters
}

In a simple form controller, we initialize the command object through setCommandName method. Now my question is how should i initialize the account object that is related to this contact?

A: 

Actually, you initialize your command object in the formBackingObject() method, which typically involves actually calling new Contact() or else using some type of factory object.

To initialize the nested objects, you pretty much have to do it by hand. Options include:

within your formBackingObject method:

Contact contact = new Contact();
contact.setAccount(new Account());

or, within the Contact object itself:

private Account account = new Account();

For more discussion, including a description of the rather more involved way that I ended up dealing with this, see my question http://stackoverflow.com/questions/378066/best-practice-for-spring-mvc-form-backing-object-tree-initialization

JacobM
thanks for the quick reply!
mahati
Instead of initializing it using the 'new', cant we do it through bean injection? what i am trying to say is, i have a contactController bean with the following definition
mahati
<bean id="contactController" class="com.advanstar.datatrax.web.action.ContactController"> <property name="commandName"> <value>contact</value> </property> <property name="commandClass"> <value>com.advanstar.datatrax.model.Contact</value> </property> which initializes the command class, now can't i say <bean id="contactBean" class="com.advanstar.datatrax.model.Contact"> <property name="account" ref="accountBean"/></bean>
mahati
to inject the account object into the contact object?
mahati
Specifying the commandClass property doesn't refer to configured beans, it just tells the controller what class the command object is (behind the scenes it just calls `BeanUtils.instantiateClass()` on that class). And you wouldn't want to simply inject a new Contact object anyway; a lot of the time you want to initialize the command bean yourself based on data in the request or in the session (e.g. someone wants to edit a Contact that already exists). That's what `formBackingObject()` is for.
JacobM
thanks again for the response, it resolves my query.
mahati
If you think your question is answered, you can click the checkbox to the left of the answer to indicate that you accept that answer.
JacobM