我有一個模型用戶和另一個模型他的國家的類。事情是這樣的:當所選選項具有空值時,將嵌套對象設置爲空
public class User{
private Country country;
//other attributes and getter/setters
}
public class Country{
private Integer id;
private String name;
//other attributes and getter/setters
}
我有一個春天的形式,我有一個組合框,使用戶可以選擇自己的國家,也可以選擇不確定的選項,以表明他doen't要提供這些信息。所以,我有這樣的事情:
<form:select path="country">
<form:option value="">-Select one-</form:option>
<form:options items="${countries}" itemLabel="name" itemValue="id"/>
</form:select>
在我的控制器中我得到了用戶信息的autopopulated對象,我想,當已經選擇了「 - 選擇單」選項,讓國家設置爲null。所以我設置了initBinder用自定義編輯器這樣的:
@InitBinder
protected void initBinder(WebDataBinder binder) throws ServletException {
binder.registerCustomEditor(Country.class, "country", new CustomCountryEditor());
}
和我的編輯做這樣的事情:
public class CustomCountryEditor(){
@Override
public String getAsText() {
//I return the Id of the country
}
@Override
public void setAsText(String str) {
//I search in the database for a country with id = new Integer(str)
//and set country to that value
//or I set country to null in case str == null
}
}
當我提交的作品,因爲當我有國家設置爲null形式當我選擇 「 - 選擇一個」選項或所選國家的實例。問題是,當我加載表單時,我有一個像下面這樣的方法來加載用戶信息。
@ModelAttribute("user")
public User getUser(){
//loads user from database
}
我從getUser()獲得的對象將國家設置爲特定的國家(不是空值),但在組合框中未選中任何選項。我已經調試了應用程序,並且CustomCountryEditor在設置和獲取文本時工作良好,但不僅爲「國家/地區」字段在列表「國家/地區」中爲每個項目調用了getAsText方法。
有什麼想法? 當我在組合框中選擇沒有國家選項時,是否有更好的方法來設置null國家對象?
感謝
我有一個數字,它在數據庫中不爲空。我已經檢查過,這個id與我的編輯器的getAsText()方法中返回的id相同。 – Javi 2010-04-16 12:07:41
你可以發佈你的編輯用戶的jsp頁面和控制器代碼。 – 2010-04-18 07:24:15