使用 jQuery 将对象数组传递给 Spring MVC 控制器

dan*_*emp 0 ajax jquery spring json spring-mvc

我有一个如下的 POJO,它包含其他 POJO 的列表:

public class Commit {

    private long revision;
    private Date date;
    private String author;
    private String comment;
    private String akuiteo;
    private List<ChangedPath> changedPathList = new ArrayList<ChangedPath>();

//Getters, Setters and Constructor following
}
Run Code Online (Sandbox Code Playgroud)

我的控制器需要 3 个参数,其中一个是数组或提交列表:

@RequestMapping(value="/selectedCommits",method=RequestMethod.POST)
@ResponseBody
public List<Commit> getAllDependentCommits(@RequestParam("branch")String branch,
@RequestParam("tag")String tagName,@RequestParam(value="commits[]") Commit[] commits) throws IOException{
    List<String> changedPaths=new ArrayList<String>();
    List<Commit> dependentCommits=UserService.listAllCommits(branch, tagName, commits);
    //UserService.createPatchFromSelectedCommits(branch, tagName, revisions);
    return dependentCommits;
}
Run Code Online (Sandbox Code Playgroud)

我也试过:List<Commit> commits而不是Commit[ ] commits

我使用 AJAX 从 jQuery 脚本调用控制器:

$("#buttonCommit").click(function(e){
console.log(branch);
console.log(tag);
console.log(selectedCommits);
$.ajax({
    url:'selectedCommits?branch='+branch+'&tag='+tag,
    method: 'POST',
    dataType: 'application/json',
    contentType: 'application/json; charset=utf-8',
    data:{
        commits:selectedCommits,
    },
    success:function(data){
        alert('wow smth really happened, here is the response : '+data[1]);
        window.selectedCommits=selectedCommits;
        window.dependentCommits=data.dependentCommits;
        console.log(data.dependentCommits);
    }
})
});
Run Code Online (Sandbox Code Playgroud)

我也试过: commits:JSON.stringify(selectedCommits)

每次我收到错误:

org.springframework.web.bind.MissingServletRequestParameterException:
Required Commit[] parameter 'commits[]' is not present
Run Code Online (Sandbox Code Playgroud)

我还测试了传递代表修订的 Long 数组并且它起作用了,我可以管理将它用于我的服务,但是拥有一个对象数组会更好。我究竟做错了什么?

Dmi*_*ich 5

你应该使用

@RequestBody List<Commit> commits
Run Code Online (Sandbox Code Playgroud)

在您的控制器中而不是

@RequestParam(value="commits[]") Commit[] commits
Run Code Online (Sandbox Code Playgroud)