如何将集合属性绑定到Spring MVC中的表单 [英] How do I bind collection attributes to a form in Spring MVC

查看:128
本文介绍了如何将集合属性绑定到Spring MVC中的表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Spring-MVC将我的一个模型对象绑定到表单的字段。一切正常,但模型对象的一个​​属性是无序集合。做类似的事情

I'm trying to bind one of my model objects to the fields of a form, using Spring-MVC. Everything works fine, except that one of the attributes of the model object is an unordered collection. Doing something like

    <c:forEach items="${m.items}" var="i" varStatus="itemsRow">
      <form:input path="items[${itemsRow.index}]"/>
    </c:forEach>
    <form:errors path="items" />

对于List类型属性可以正常工作,但是对于Set,在提交时会引发错误,它试图将输入字段内容绑定到对象属性。

would work fine for a List-type property, but for a Set throws an error when, upon submit, it tries to bind input field content to object attributes.

Spring中有什么东西可以开箱即用吗?

Is there something in Spring that works out of the box with Sets?

推荐答案

我认为它必须是一个有序的集合。例如,Spring参考中有图表讨论如何引用属性。它说:

I think it has to be an ordered collection. For example,there's a chart in the Spring reference that talks about how to reference properties. It says:


account [2]表示索引属性帐户的第三个元素

索引属性的类型可以是
数组,列表或其他自然排序的
集合(强调他们的)

account[2] Indicates the third element of the indexed property account. Indexed properties can be of type array, list or other naturally ordered collection (emphasis theirs)

也许一种方法是向对象添加一个getter,而不是返回你的Set,返回Set.toArray()。然后您的items属性将引用该数组。当然,你不能依赖订购。

Perhaps one approach would be to add a getter to your object that, rather than returning your Set, returns Set.toArray(). Then your items attribute would reference the array. Of course, you can't depend on the ordering.

这篇关于如何将集合属性绑定到Spring MVC中的表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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