【发布时间】:2010-04-15 10:08:19
【问题描述】:
我有一个模拟用户的类和另一个模拟他的国家的类。像这样的:
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
}
我有一个 Spring 表单,其中有一个组合框,因此用户可以选择他的国家或可以选择未定义的选项来表明他不想提供此信息。所以我有这样的事情:
<form:select path="country">
<form:option value="">-Select one-</form:option>
<form:options items="${countries}" itemLabel="name" itemValue="id"/>
</form:select>
在我的控制器中,我得到带有用户信息的自动填充对象,并且我希望在选择“-Select one-”选项时将国家/地区设置为空。所以我用这样的自定义编辑器设置了一个 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
}
}
当我提交表单时它可以工作,因为当我选择时将国家/地区设置为空 “-Select one-”选项或所选国家的实例。问题是当我加载表单时,我有一个类似下面的方法来加载用户信息。
@ModelAttribute("user")
public User getUser(){
//loads user from database
}
我从 getUser() 获得的对象已将国家/地区设置为特定国家/地区(不是空值),但在组合框中未选择任何选项。我已经调试了应用程序,并且 CustomCountryEditor 在设置和获取文本时运行良好,尽管 getAsText 方法对“国家”列表中的每个项目都调用,而不仅仅是“国家”字段。
有什么想法吗? 当我在组合框中未选择国家/地区选项时,是否有更好的方法将国家/地区对象设置为空?
谢谢
【问题讨论】:
标签: java spring data-binding null spring-mvc