如何将对象列表绑定到SpringMvc Controller?

goe*_*ing 2 java binding spring spring-mvc

我在SpringMvc应用程序上使用以下操作:

@RequestMapping(value = "/test", method = RequestMethod.GET)
public ModelAndView test(
    @ModelAttribute List<Group> groups
) { 
 //return whatever
}
Run Code Online (Sandbox Code Playgroud)

我的Group类有一个'id'和'name'属性.默认的getter/setter.我应该如何调用此操作才能正确实现此列表?

我试过类似的东西:/
test?groups.id = 2&groups.name = stackrocks&groups.id = 3&groups.name = stackrules
不起作用.

还尝试了:/
test?groups [].id = 2&groupss [].name = stackrocks&groupss [] .id = 3&groupss [].name = stackrules
没有成功.

那么,在使用SpringMvc时如何绑定列表?

axt*_*avt 6

您不能将方法的参数与该签名完全绑定.@ModelAttribute将属性绑定到相应模型对象的字段,因此您可以封装List到对象中:

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  
}  
Run Code Online (Sandbox Code Playgroud)

然后按如下方式调用它:

/test?list[0].id=2&list[0].name=stackrocks&list[1].id=3&list[1].name=stackrules
Run Code Online (Sandbox Code Playgroud)