如何将对象列表绑定到 SpringMvc 控制器? [英] How to bind a list of object to SpringMvc Controller?
问题描述
我在 SpringMvc 应用程序上使用以下操作:
I'm using the following action on a SpringMvc application:
@RequestMapping(value = "/test", method = RequestMethod.GET)
public ModelAndView test(
@ModelAttribute List<Group> groups
) {
//return whatever
}
我的 Group 类有一个 'id' 和一个 'name' 属性.默认的 getter/setter.我应该如何调用此操作才能正确实例化此列表?
My Group class has an 'id' and a 'name' property. Default getter/setter. How should i call this action in order to have this list correctly instanciated?
我尝试过类似的方法:
/test?groups.id=2&groups.name=stackrocks&groups.id=3&groups.name=stackrules
没用.
I tried something like:
/test?groups.id=2&groups.name=stackrocks&groups.id=3&groups.name=stackrules
Didn't work.
也试过了:
/test?groups[].id=2&groups[].name=stackrocks&groups[].id=3&groups[].name=stackrules
没有成功.
Also tried:
/test?groups[].id=2&groups[].name=stackrocks&groups[].id=3&groups[].name=stackrules
No success.
那么,使用 SpringMvc 时如何绑定列表?
So, how to bind a list when using SpringMvc?
推荐答案
您不能将方法的参数与该签名完全绑定.@ModelAttribute
将属性绑定到对应模型对象的字段上,这样你就可以将你的List
封装成对象:
You can't bind parameters of method with the exactly that signature. @ModelAttribute
binds attributes to the fields of the corresponding model object, so you can encapsulate your List
into object:
public class Groups {
private List<Group> list = new AutoPopulatingList<Group>(Group.class);
...
}
@RequestMapping(value = "/test", method = RequestMethod.GET)
public ModelAndView test(
@ModelAttribute Groups groups
) {
//return whatever
}
然后按如下方式调用它:
and then call it as follows:
/test?list[0].id=2&list[0].name=stackrocks&list[1].id=3&list[1].name=stackrules
这篇关于如何将对象列表绑定到 SpringMvc 控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!