Spring - binding to an object, not to String or primitive

Say I have the following command object:

class BreakfastSelectCommand{ List<Breakfast> possibleBreakfasts; Breakfast selectedBreakfast; } 

How can I spring fill "selectedBreakfast" with breakfast from the list?

I decided that in my jsp I would do something like this:

 <form:radiobuttons items="${possibleBreakfasts}" path="selectedBreakfast" /> 

But this does not seem to work. Any ideas?

thanks,

-Morgan

+6
spring spring-mvc data-binding
source share
1 answer

The key to this is the PropertyEditor.

You need to define a PropertyEditor for your Breakfast class, and then configure ServletDataBinder using registerCustomEditor in your controller's initBinder method.

Example:

 public class BreakfastPropertyEditor extends PropertyEditorSupport{ public void setAsText(String incomming){ Breakfast b = yourDao.findById( Integer.parseInt(incomming)); setValue(b); } public String getAsText(){ return ((Breakfast)getValue()).getId(); } } 

note that you will need some kind of zero check, etc., but you get this idea. In the controller:

 public BreakfastFooBarController extends SimpleFormController { @Override protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) { binder.registerCustomEditor(Breakfast.class, new BreakfastPropertyEditor(yourDao)); } } 

things to pay attention to:

  • PropertyEditor are not thread safe
  • if you need spring beans, either manually enter them, or define them in spring as the prototype area and use the input method in your controller
  • throw IllegalArgumentException, if the input parameter is invalid / not found, spring will correctly convert this to a binding error

hope this helps.

Edit (in response to comment): In this example, this looks a little strange, because BreakfastSelectCommand is not like an entity, I'm not sure what your actual scenario is. Let's say that this is an object, for example, Person with the breakfast property, then the formBackingObject() method will load the Person object from PersonDao and return it as a command. The binding phase will then change the breakfast property depending on the value selected, so that the command that arrives on onSubmit has the breakfast property, all configured.

Depending on the implementation of your DAO objects, calling them twice, or trying to load the same object twice, does not really mean that you will get two SQL statements. This applies, in particular, to Hibernate, where it guarantees that it will return the same object as in it for the given identifier, therefore the launch, which allows the attempt to bind to load the breakfast selection, even through it, has not changed, should not in any excessive service data.

+8
source share

All Articles