Spring MVC形式:选择标签,多个选择不能正确绑定?


问题内容

我正在尝试创建一个表单来编辑现有数据库行。我正在使用Spring
MVC表单标签将html自动绑定到表单支持对象。该行与另一个表具有多对多关系,我正尝试使用form:select标记的多重选择框来表示该关系。

<form:select path="rules">
    <form:options items="${bundle.rules}" itemValue="name" itemLabel="name"/>
</form:select>

我使用Hibernate进行持久化,因此该关系表示为Bundle pojo中的HashSet。

 private Set<Rule> rules = new HashSet<Rule>(0);

没有页面上的选择框,该对象将正确更新到数据库,但是使用选择框,该对象将不会更新到数据库,并且我在log4j日志中收到此错误,请注意,此错误不会引起异常,仅在日志中可见;

DEBUG org.springframework.web.servlet.mvc.SimpleFormController.processFormSubmission(SimpleFormController.java:256) - Data binding errors: 1

无论我是否取消选择框内的项目,都会发生这种情况,整个表单都会拒绝正确提交。谁能帮我?

我知道如何在Spring MVC中将集合属性绑定到表单,这与此问题类似,但是不幸的是,这些建议似乎都对我的问题没有帮助。


问题答案:

问题在于您提交表单。Spring无法绑定命令的对象,因此它不提交表单,而是将您重定向到formView。

成功执行绑定后,您将看到以下消息:

No errors -> processing submit

要解决您的问题,您将需要向控制器注册一个CustomCollectionEditor。(请参阅此链接)。就像这样:

protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception
{   
  binder.registerCustomEditor(Set.class, "rules", new CustomCollectionEditor(Set.class)
  {
    protected Object convertElement(Object element)
    {
        String name = "";

        if (element instanceof String)
            name = (String) element;

        return name != null ? new Rule(name) : null;
    }
  });
}