Spring MVC窗体:选择标签,多选不能正确绑定? [英] Spring MVC form:select Tag, multiple selections not binding correctly?

查看:122
本文介绍了Spring MVC窗体:选择标签,多选不能正确绑定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个表单来编辑现有的数据库行。我正在使用Spring MVC窗体标签来自动绑定HTML到窗体支持对象。该行与另一个表具有多对多关系,我试图用多选框表示:select tag;

I am trying to create a form to edit an existing database row. I am using the Spring MVC form tag to auto bind the html to a form backing object. The row has a many to many relationship with another table, which I am trying to represent with a multiple select box using the form:select tag;

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

我使用Hibernate进行持久化,所以关系在Bundle pojo中表示为HashSet。 p>

I am using Hibernate for persistence so the relationship is represent as a HashSet inside the Bundle pojo.

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

如果没有页面上的选择框,对象会正确更新到数据库,但是通过选择该对象不会更新到数据库,我在我的log4j日志中发现了这个错误,注意这个错误不会引发异常,它只在日志中可见;

Without the selection box on the page, the object will update to the database correctly, however with the selection box the object will not update to the database and I am getting this error in my log4j log, note that this error is not causing an exception, it is only visible in the logs;

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

发生这种情况无论我在选择框中取消选择项目,整个表单都拒绝正确提交。任何人都可以帮助我?

This happens regardless of wither I deselect items inside the select box, the entire form refuses to submit correctly. Can anyone help me?

我知道,这与此问题类似,不幸的是,没有任何建议对我的问题有用。

I am aware of How do I bind collection attributes to a form in Spring MVC, which is similar to this question, unfortunately none of the suggestions seemed useful to my problem.

推荐答案

问题出在提交表单的时候。 Spring不能绑定命令的一个对象,所以它不会提交表单,而是将您重定向到formView。

The problem is with the submission of your form. Spring isn't able to bind an object of the command, so it doesn't submit the form, but redirects you to the formView instead.

当绑定成功时你会看到这个消息:

When the binding is successfully performed, you will see this message instead:

No errors -> processing submit

要解决您的问题,您需要在您的控制器中注册一个CustomCollectionEditor。 (请参阅链接)。它会是这样的:

To solve your problem, you will need to register a CustomCollectionEditor with your controller. (See this link). It would be something like this:

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;
    }
  });
}

这篇关于Spring MVC窗体:选择标签,多选不能正确绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆