Nested Data Binding Customization in Spring
As covered elsewhere, Spring's MVC databinding can be customized using the ServletRequestDataBinder's registerCustomEditor methods. In most cases, you specify just the data type or a combination of data type and field name (for field-specific data binding rules).
I ran into trouble trying to customize the data binding of a nested Collection component's field. It turns out it's just as easy, just not very intuitive.
To register a custom PropertyEditor for a nested field, you use the same method as a non-nested field, but you use a special syntax for the field name. The following is a hypothetical example binding an Order object. The Order contains a field called customer, which is of type Person. The Person class has its own field birthDate.
protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception
{
super.initBinder(request, binder);
binder.registerCustomEditor(Date.class, "customer.birthDate", new CustomDateEditor(new SimpleDateFormat("M/d/y"), true));
}
To my surprise, binding an object inside of a Collection object is done exactly the same way. Here's a hypothethetical example. Once again, Order is the object being bound (the command in Spring-speak). It has a field items that is a List of OrderItem objects. OrderItem has a field quantity.
binder.registerCustomEditor(Integer.class, "items.quantity", new CustomNumberEditor(Integer.class, false));

On the view end for the
On the view end for the first example, did you do
#springBind( "order.customer.birthDate" ) ?
I got an error though if so.
Invalid property 'customer' of bean class [com.foo.model.order.Order]: Value of nested property 'customer' is null
=/
Post new comment