我有一个类来模拟用户,还有一个类来模拟他的国家。大致如下:
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>
在我的控制器中,我获取了自动填充的包含用户信息的对象,并且当选择“- 请选择 -”选项时,我希望将国家设置为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()获取的对象中,国家已设置为特定国家(不是null值),但在下拉框中没有选中任何选项。我已经调试了应用程序,并且CustomCountryEditor在设置和获取文本时工作良好,尽管getAsText方法对于列表“countries”中的每个项目都被调用,而不仅仅是“country”字段。
有任何想法吗? 是否有更好的方法,在下拉框中选择无国家选项时将国家对象设置为null?
谢谢