Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring form binding how to do it ? Cannot convert value of type [java.lang.String] to required type

here is my form :

<form:form modelAttribute="fooDTO">
fooCountry: 
<form:select path="country">
  <form:options items="${countries}" itemLabel="shortName" itemValue="id"/> 
</form:select>

here is the backing pojo :

public class FooDTO
{
  private Country country;
 //getters and setters present
}

The selected option defaults to the country value in fooDTO, which is good. But the binding then fails when submitting the form - I get the aformentioned error, do I have to register a custom editor in a binder, or is there a simpler method ? Country is pretty much as you'd expect, and countries is indeed a list of countries populated in the controller ...

like image 968
NimChimpsky Avatar asked Feb 23 '12 16:02

NimChimpsky


2 Answers

Change your path to <form:select path="country.id">. That will at least give you the id field popluated inside the Country object upon posting.

like image 120
GriffeyDog Avatar answered Oct 17 '22 12:10

GriffeyDog


Spring 3 introduced the Converter SPI which makes this quite easy. Have a look at 6.5 in the documentation

Taking source from the docs and putting in your country, you would do something like

package my.converter;

final class StringToCountry implements Converter<String, Country> {
    public Country convert(String source) {
        return // whatever you do to get a country from your string
    }
}

Then in the xml config you would configure the converter

<bean id="conversionService"
      class="org.springframework.context.support.ConversionServiceFactoryBean">
    <property name="converters">
        <list>
            <bean class="my.converter.StringToCountry"/>
        </list>
    </property>
</bean>

As GriffeyDog pointed out, you may want to put the country id in for the select path so you can get the Country by ID or something instead of whatever is returned by toString() of your Country object.

like image 38
digitaljoel Avatar answered Oct 17 '22 11:10

digitaljoel