【问题标题】:Setting nested object to null when selected option has empty value当所选选项具有空值时将嵌套对象设置为NULL
【发布时间】: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


    【解决方案1】:

    问题是我从 Spring Security 主体对象中检索对象用户。我已经更改了我的 getUser 方法,所以我从 Spring Security 获取 Id 并在数据库中搜索,现在一切正常,但我不明白为什么会发生这种情况,因为我可以在调试中看到该国家/地区已由 Spring 加载到用户中安全性。

    【讨论】:

      【解决方案2】:

      您是否检查了数据库表中的用户,当您保存用户时正在为国家/地区设置什么值......它是否为空,是否有一些值?

      【讨论】:

      • 我有一个数字,它在数据库中不为空。我检查了这个 id 是否与我的编辑器的 getAsText() 方法中返回的数字相同。
      • 你能发布你的jsp页面和控制器代码来编辑用户吗?
      猜你喜欢
      • 2019-04-23
      • 1970-01-01
      • 2019-09-05
      • 2014-09-12
      • 1970-01-01
      • 2016-08-20
      • 2013-04-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多