Ajax POST 对象数组到 Spring MVC Controller - 多个错误

标签 ajax spring spring-boot spring-mvc

我需要将一个 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”不存在]

还尝试使用 ModelAttributeArrayList

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/

相关文章:

php - Json 获取队列

ajax - AngularJS和Spring Security取消了AJAX请求

spring-boot - swagger 两次添加上下文根

java - app.yaml vs appengine-web.xml 使用哪一个?

php - 在表单中添加 Action 变量

jquery tablesorter + ajax div内容更新问题

java - Spring 需要的 CassandraTemplate.execute 批处理语句帮助

java - 使用 Spring Boot 进行 ANSI 日志记录

java - Spring MVC 中的 Ajax 无法正常工作

spring - 无法将查询字符串参数映射到我的JavaBean(使用Spring 4和Datatables)