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

发布于 2024-12-10 12:04:37 字数 1233 浏览 2 评论 0 原文

我有一个带有 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 看起来像实际值的单元素数组的数组:

Expected (things in initBinder):

[value1, value2, value3]

Get in doSaveMyDTO (myDTO. getThings()):

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

为什么?请解释一下...

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...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

肥爪爪 2024-12-17 12:04:37

如果请求格式正确(things=v1&things=v2&things=v3things=v1,v2,v3),spring 的内置转换器应该正确转换将其添加到 List - 无需注册您自己的列表。

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文