我需要将一个 JS 格式的对象数组提交给 Spring MVC Controller 。所有属性名称都匹配。
@PostMapping("/addAdmin")
public void addAdmin(@RequestParam List<UserRolesGUIBean> userRolesGUIBeans)
{
// ...
}
JS:
var entries = [];
//...
// entries is an array of objects of the form {id: "..", role: ".."}
// verified to be correct before submission
$.ajax({
type : "post",
dataType : "json",
url : 'addAdmin',
data : JSON.stringify(entries)
})
bean
public class UserRolesGUIBean implements Serializable {
private String id;
private String role;
// + Constructors (Empty + Full), Getters and setters
}
错误:
必需的列表参数“userRolesGUIBeans”不存在]
还尝试使用 ModelAttribute
和 ArrayList
,
PostMapping("/addAdmin")
public void addAdmin(@ModelAttribute ArrayList<UserRolesGUIBean> userRolesGUIBeans) {
现在没有错误,但是列表是空的,没有收到数据。
尝试了一切——数组与列表,JSON.stringify(data)
或带有 data {"entries": entries}
的数据对象,RequestBody
不起作用并给出 UTF 错误;和上面的 RequestParam
也不起作用。
这对于一项简单的任务来说太复杂了。
最佳答案
您正在尝试使用帖子发送 JSON 对象。您应该使用 @RequestBody
注释。
尝试以这种方式改变你的方法:
@PostMapping("/addAdmin")
public void addAdmin(@RequestBody List<UserRolesGUIBean> userRolesGUIBeans)
{
// ...
}
这样Spring会拦截Json并将其转换成List of wished objects
关于Ajax POST 对象数组到 Spring MVC Controller - 多个错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56063774/