Spring表单绑定怎么做?无法将[java.lang.String]类型的值转换为所需类型 [英] Spring form binding how to do it ? Cannot convert value of type [java.lang.String] to required type

查看:213
本文介绍了Spring表单绑定怎么做?无法将[java.lang.String]类型的值转换为所需类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的表格:

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

这里是支持pojo:

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

所选期权默认为fooDTO中的国家价值,这很好。但是提交表单时绑定失败了 - 我得到了上述错误,我是否必须在活页夹中注册自定义编辑器,还是有更简单的方法?国家就像你期望的那样,国家确实是控制器中填充的国家名单......

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 ...

推荐答案

Spring 3引入了转换器SPI,这使得它非常简单。看看文档

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
    }
}

然后在xml配置中配置转换器

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>

正如GriffeyDog指出的那样,您可能希望将国家ID放入选择路径,这样您就可以通过ID或其他东西获取Country,而不是Country对象的toString()返回的内容。

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.

这篇关于Spring表单绑定怎么做?无法将[java.lang.String]类型的值转换为所需类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆