arahant
arahant

Reputation: 2203

Spring MVC - bind enum array

If I post in the format weather=sunny, Spring MVC happily converts this to an Weather enum instance using the enum with name=sunny.

However if I post weather=sunny&weather=windy, then Spring is not able to convert it into an instance of Weather[]. The error I get is:

Failed to convert property value of type 'java.lang.String[]' to required type 'com.blah.Weather[]' for property 'weather'

How can I achieve this?

Upvotes: 3

Views: 1971

Answers (1)

Bhashit Parikh
Bhashit Parikh

Reputation: 3131

You can use Converters to perform the custom conversion. For your example, you would need to do something like:

public class WeatherConverter implements Converter<String[], Weather[]> {

    @Override
    public Weather[] convert(String[] source) {
        if(source == null || source.length == 0) {
            return new Weather[0];
        }
        Weather[] weathers = new Weather[source.length];
        int i = 0;
        for(String name : source) {
            weathers[i++] = Weather.valueOf(name); 
        }
        return weathers;
    }

}

You can use Converters anywhere you might want type-conversions. Now, what you need to do is register it:

<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
    <property name="converters">
        <list>
            <bean class="package.path.WeatherConverter"/>
        </list>
    </property>
</bean>

And it is done.

You can see more details in the Spring Reference.

You could also look into PropertyEditors, with @InitBinder, and, probably, @ControllerAdvice if you want. However, Converters are much easier to use (IMO).

Upvotes: 5

Related Questions