Spring MVC Binding: How to bind ArrayList<…>?

妖精的绣舞 提交于 2019-12-23 05:17:42

问题


I've got a DTO (bean) with ArrayList field:

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

In my initBinder I have:

@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);
    }
  });
}

And in my controller request method:

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

The problem is that while I'm in registerCustomEditor staff the things array is ok.

But when I get to the doSaveMyDTO method - MyDTO.things looks like Array of one element arrays of actual values:

Expected (things in initBinder):

[value1, value2, value3]

Get in doSaveMyDTO (myDTO.getThings()):

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

Why? Please explain...


回答1:


If the request is correctly formed (things=v1&things=v2&things=v3 or things=v1,v2,v3), spring's built-in converters should properly convert it to a List - no need to register your own.

If your input is JSON, then you'd need @RequestBody instead of @ModelAttribute



来源:https://stackoverflow.com/questions/7794847/spring-mvc-binding-how-to-bind-arraylist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!