spring-mvcspring-mvc-initbinders

Custom Binding Required for SpringMVC Form Field


I ran into the following SpringMVC issue: there is a domain object which uses a certain Address sub-object, but the getters/setters have to be tweaked to use a different Address object via conversion. This is an architectural requirement.

public class DomainObj {
    protected DomainObj.Address address;

    public anotherpackage.new.Address getAddress()
    {
       return convertFrom(address);
    }

    public void setAddress (anotherpackage.new.Address value)
    {
        this.address = convertTo(value);
    }

}

// Internal Address object, old, #1
public static class Address {
     protected String street1;
     protected String street2;
     // etc., getters/setters
}

Now, in the JSP, I bind an Input Text Field to the new Address object (the result of conversions) that's what we have to deal with. In this new 2nd Address object (anotherpackage.new.Address), there is a field e.g. "addressLine1", which is different from the old object's "Street1":

<form:input path="topObject.address.addressLine1" />

My problem is that the setter, setAddress(), never gets called in this case for binding (verified in the Debugger). Any solutions to this?


Solution

  • Your options are:

    a) do not bind directly to the business object b) configure a binder to do the conversion to your domain object

    Discussion:

    Usually in enterprise class software we don't want to bind directly to the business objects -- which are usually entities (in the context of jpa). This is because session handling is a bee-otch. Usually we code against DTOs, and when one is received from the front-end we read the appropriate object from the repository (ORM) layer, update it, and save it back again (I've only described updates because they're the hardest, but a similar model works for everything).

    However, spring mvc binders offer a way of binding anything to anything. They're a bit complicated and it'll take too long to explain here, but the docs are in the spring documentation and you want to be looing at converters and a conversion service. There are SO Q/A's on this topic, for example...