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


问题内容

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

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

我的组类具有“ id”和“ name”属性。默认的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将属性绑定到相应模型对象的字段,因此可以将其封装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  
}

然后按如下方式调用它:

/test?list[0].id=2&list[0].name=stackrocks&list[1].id=3&list[1].name=stackrules