2012-10-13 52 views
12

我有一个模型,其中包含国家(列表)和持有国家对象的用户对象的列表。我有一个观点,用户可以选择他的国家。
这是我的JSP页面的代码片段:春天mvc窗体:选择标记

<form:select path="user.country"> 
    <form:option value="-1">Select your country</form:option> 
    <form:options items="${account.countries}" itemLabel="name" itemValue="id" /> 
</form:select> 

这是我的帐号模式:

public class Account { 

    private User user; 
    private List<Country> countries; 

    public User getUser() { 
     return user; 
    } 

    public void setUser(User user) { 
     this.user = user; 
    } 

    public List<Country> getCountries() { 
     return countries; 
    } 

    public void setCountries(List<Country> countries) { 
     this.countries = countries; 
    } 
} 

当JSP负载(GET)形式:选择显示当前用户的选择项国家。问题是,当我发帖的形式,我得到这个异常:

Field error in object 'account' on field 'user.country': rejected value [90]; 
    codes [typeMismatch.account.user.country,typeMismatch.user.country,typeMismatch.country,typeMismatch.org.MyCompany.entities.Country,typeMismatch]; 
    arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [account.user.country,user.country]; 
    arguments []; default message [user.country]]; 
    default message [Failed to convert property value of type 'java.lang.String' to required type 'org.MyCompany.entities.Country' for property 'user.country'; 
    nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [org.MyCompany.entities.Country] for property 'country': no matching editors or conversion strategy found] 

任何想法如何,我可以解决这个?

回答

7

您需要以某种方式告诉Spring将String转换为Country。这里有一个例子:

@Component 
public class CountryEditor extends PropertyEditorSupport { 

    private @Autowired CountryService countryService; 

    // Converts a String to a Country (when submitting form) 
    @Override 
    public void setAsText(String text) { 
     Country c = this.countryService.findById(Long.valueOf(text)); 

     this.setValue(c); 
    } 

} 

... 
public class MyController { 

    private @Autowired CountryEditor countryEditor; 

    @InitBinder 
    public void initBinder(WebDataBinder binder) { 
     binder.registerCustomEditor(Country.class, this.countryEditor); 
    } 

    ... 

} 
+0

谢谢 - 这奏效了。有一件事我还不明白。如果我在发布数据时需要定制转换器,为什么在获取数据时我不需要一个? (当页面加载时,选定的国家与用户具有相同的国家对象) –

+0

@MTT。 Spring MVC巧妙地处理'select'形式。你的'form:select'具有'path =“user.country”'。因此,如果用户已经有一个ID为42的国家,那么值为42的选项标签将具有“selected =”选择的“'属性。有关更多信息,请查看关于选择标签的文档(点击此处)](http://static.springsource.org/spring/docs/current/spring-framework-reference/html/view.html#view-jsp-formtaglib -selecttag)。 –

+0

太棒了!工作完美的人,我想更多地了解这是如何工作的。 – Gemasoft