Spring表单绑定怎么做? 无法将类型的值转换为所需类型

这是我的表格:

fooCountry:

这是支持pojo:

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

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

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

从文档中获取信息并放入你的国家,你会做类似的事情

 package my.converter; final class StringToCountry implements Converter { public Country convert(String source) { return // whatever you do to get a country from your string } } 

然后在xml配置中,您将配置转换器

        

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

将您的路径更改为 。 这至少会在发布时为您提供在Country对象中弹出的id字段。

问题是Spring看到了一个String实例,但知道它需要一个Country实例。 它默认不“知道”如何从一个到另一个。

我之前没有使用过Spring表单绑定,但这看起来与Spring框架本身可能遇到的问题相同。 在后一种情况下,您可以通过为您的类注册PropertyEditor实现来解决它,因此我希望类似的方法可以在这里工作。

在Spring中,您还可以使用ConversionService

这是文档: http : //static.springsource.org/spring/docs/current/spring-framework-reference/html/validation.html#format-configuring-FormattingConversionService

您需要实现Converter接口。

看看我的解决方案:

 public class CompanyIdToInstanceConverter implements Converter { @Autowired CompanyService _companyService; @Override public Company convert(final String companyIdStr) { return _companyService.find(Long.valueOf(companyIdStr)); } } 

通过从DB获取公司ID,将公司ID从select转换为Company。

如果您有任何其他问题,请询问,因为现在我在我的应用程序中做类似的事情:)

此外,您需要添加到app-context:

     toryLabelConverter">     

如果您正在处理MVC应用程序,请参阅此Spring Source论坛链接,了解如何配置应用程序上下文。 细节位于主题的底部。

conversionService类与MVC不同,您需要指定mvc:annotation-driven(即使您没有使用注释)。

http://forum.springsource.org/showthread.php?84003-Converters-no-matching-editors-or-conversion-strategy-found

您将在Spring文档中找到具体内容: http : //static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html/validation.html#format-configuring-formatting-mvc