Spring MVC绑定:如何绑定ArrayList< ...>?

时间:2011-10-17 13:56:14

标签: spring binding spring-mvc

我有一个带ArrayList字段的DTO(bean):

public MyDTO {
  ...
  private List<MyThing> things;
  ...
  ... getters, setters and so on
}

在我的initBinder中,我有:

@InitBinder
public void initBinder(WebDataBinder binder) {
  ...
  binder.registerCustomEditor(List.class, "things", new PropertyEditorSupport() {
    @Override
    public void setAsText(String text) throws IllegalArgumentException {
       List<MyThing> things = new ArrayList<MyThings>;

       // fill things array with data from text
       ...


       // On that stage things value is correct!
       super.setValue(things);
    }
  });
}

在我的控制器请求方法中:

@RequestMapping({"save"})
public ModelAndView doSaveMyDTO(@ModelAttribute MyDTO myDTO) {
  // very strange myDTO comes here=(
}

问题在于,当我在registerCustomEditor工作人员时,things阵列正常。

但是当我到达doSaveMyDTO方法时,MyDTO.things看起来像一个实际值的元素数组的数组:

预期(initBinder中的内容):

[value1, value2, value3]

进入doSaveMyDTO(myDTO.getThings()):

[[value1], [value2], [value3]]

为什么呢?请解释......

1 个答案:

答案 0 :(得分:2)

如果请求正确形成(things=v1&things=v2&things=v3things=v1,v2,v3),spring的内置转换器应该正确地将其转换为List - 无需注册您自己的。

如果您的输入是JSON,那么您需要@RequestBody而不是@ModelAttribute

相关问题