当所选选项为空值时,将嵌套对象设置为null。

4

我有一个类来模拟用户,还有一个类来模拟他的国家。大致如下:

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?

谢谢

2个回答

1
问题在于我从Spring Security principal对象中检索了User对象。我已经更改了我的getUser方法,所以我从Spring Security获取Id,然后在数据库中搜索,现在一切都正常了,虽然我不明白为什么会发生这种情况,因为我可以在调试中看到国家被Spring Security加载到用户中。

0
你有检查过用户数据库表吗?当你保存用户时,国家的值被设置为什么?是空值还是有某个值?


我有一个数字,在数据库中不为空。我已经检查过,这个ID与我的编辑器的getAsText()方法返回的数字相同。 - Javi
你能否发布编辑用户的JSP页面和控制器代码? - Hussain Fakhruddin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接