开发者

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

开发者 https://www.devze.com 2023-04-13 08:39 出处:网络
I\'ve got a DTO (bean) with ArrayList field: public MyDTO { ... private List<MyThing> things; ... ... getters, setters and so on

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 IllegalArgume开发者_Go百科ntException {
       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...


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号