使用jQuery将对象数组传递给Spring MVC控制器 [英] Pass array of objects to Spring MVC controller using jQuery

查看:120
本文介绍了使用jQuery将对象数组传递给Spring MVC控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a POJO as follows, it contains a list of other POJOs:

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
}

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

My controller expects 3 parameters one of them being an array or a list of Commit:

@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;
}

我也尝试过:List<Commit> commits代替Commit[ ] commits

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

I call the controller from a jQuery script using AJAX:

$("#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);
    }
})
});

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

每次我收到错误消息:

org.springframework.web.bind.MissingServletRequestParameterException:
Required Commit[] parameter 'commits[]' is not present

我还测试了传递代表修订版本的Long数组,并且该数组有效,我可以管理将其用于我的服务,但是拥有对象数组会更好.我究竟做错了什么?

I have also tested passing an array of Long representing the revisions and it worked, I can manage using it for my services but it would be nicer to have an array of objects. What am I doing wrong?

推荐答案

您应该使用

@RequestBody List<Commit> commits

在您的控制器中,而不是

in your controller instead of

@RequestParam(value="commits[]") Commit[] commits

这篇关于使用jQuery将对象数组传递给Spring MVC控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆