【问题标题】:Spring MVC Binding: How to bind ArrayList<...>?Spring MVC 绑定:如何绑定 ArrayList<...>?
【发布时间】:2011-10-17 13:56:14
【问题描述】:

我有一个带有 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]]

为什么?请解释...

【问题讨论】:

    标签: spring binding spring-mvc


    【解决方案1】:

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

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

    【讨论】:

    • 不幸的是,我的列表是一个 json 字符串。无论如何,感谢您的建议 - 我会尽力按照您的方式制作它...
    • 啊,json 是另外一回事。你的 json 是什么样子的?为此,我认为你们很多人需要@RequestBody
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多