Spring MVC 绑定:如何绑定 ArrayList<...>?
我有一个带有 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]]
为什么?请解释一下...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果请求格式正确(
things=v1&things=v2&things=v3
或things=v1,v2,v3
),spring 的内置转换器应该正确转换将其添加到List
- 无需注册您自己的列表。如果您的输入是 JSON,那么您需要
@RequestBody
而不是@ModelAttribute
If the request is correctly formed (
things=v1&things=v2&things=v3
orthings=v1,v2,v3
), spring's built-in converters should properly convert it to aList
- no need to register your own.If your input is JSON, then you'd need
@RequestBody
instead of@ModelAttribute