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