如何绑定对象来控制用SpringMVC一个列表? [英] How to bind a list of object to SpringMvc Controller?
问题描述
我使用一个应用程序用SpringMVC以下动作:
@RequestMapping(值=/测试,方法= RequestMethod.GET)
公共ModelAndView的测试(
@ModelAttribute名单<组>组
){
//返回什么
}
我的组类有一个'身份证'和'名'属性。默认的getter / setter。
我应该怎么称呼这个动作才能有这份名单正确实例化?
我想是这样的:结果
/test?groups.id=2&groups.name=stackrocks&groups.id=3&groups.name=stackrules结果
没有工作。
也试过:结果
/test?groups[].id=2&groups[].name=stackrocks&groups[].id=3&groups[].name=stackrules结果
没有成功。
那么,如何用SpringMVC使用时绑定列表?
您无法使用正是签名绑定方法的参数。 @ModelAttribute
属性绑定到相应的模型对象的字段,所以您可以封装你的列表
成目标:
公共类组{
私人列表<组>名单=新AutoPopulatingList<组>(Group.class);
...
}@RequestMapping(值=/测试,方法= RequestMethod.GET)
公共ModelAndView的测试(
@ModelAttribute组组
){
//返回什么
}
,然后调用它,如下所示:
<$p$p><$c$c>/test?list[0].id=2&list[0].name=stackrocks&list[1].id=3&list[1].name=stackrulesI'm using the following action on a SpringMvc application:
@RequestMapping(value = "/test", method = RequestMethod.GET)
public ModelAndView test(
@ModelAttribute List<Group> groups
) {
//return whatever
}
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?
I tried something like:
/test?groups.id=2&groups.name=stackrocks&groups.id=3&groups.name=stackrules
Didn't work.
Also tried:
/test?groups[].id=2&groups[].name=stackrocks&groups[].id=3&groups[].name=stackrules
No success.
So, how to bind a list when using SpringMvc?
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屋!