我有一个带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]]
为什么呢?请解释......
答案 0 :(得分:2)
如果请求正确形成(things=v1&things=v2&things=v3
或things=v1,v2,v3
),spring的内置转换器应该正确地将其转换为List
- 无需注册您自己的。
如果您的输入是JSON,那么您需要@RequestBody
而不是@ModelAttribute