Let’s say I have the following command object:
class BreakfastSelectCommand{ List<Breakfast> possibleBreakfasts; Breakfast selectedBreakfast; }
How can I have spring populate ‘selectedBreakfast’ with a breakfast from the list?
I was figuring I’d do something like this in my jsp:
<form:radiobuttons items='${possibleBreakfasts}' path='selectedBreakfast' />
But this doesn’t seem to work. Any ideas?
thanks,
-Morgan
The key to it all of this is the PropertyEditor.
You need to define a PropertyEditor for your Breakfast class and then configure the ServletDataBinder using registerCustomEditor in the initBinder method of your controller.
example:
note you’ll be needing some null checking etc, but you get the idea. In your controller:
things to watch out for:
hope this helps.
Edit (in response to the comment): It looks a little strange in the given example because BreakfastSelectCommand doesn’t look like an entity, I’m not sure what the actual scenario you have is. Say it is an entity, for example like
Personwith abreakfastproperty then theformBackingObject()method would load the Person object from the thePersonDaoand return it as the command. The binding phase would then change the breakfast property depending on the selected value, such that the command that arrives inonSubmithas the breakfast property all set up.Depending on the implementation of your DAO objects calling them twice or attempting to load the same entity twice doesn’t actually mean that you will get two SQL statements being run. This applies particularly to Hibernate, where it guarantees that it will return the same object that is in it’s session for a given identifier, thus running letting the binding attempt to load the
Breakfastselection even through it hasn’t changed shouldn’t result in any undue overhead.