我有一个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
}
我的控制器需要3个参数,其中一个是数组或一个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脚本调用控制器:
$("#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数组并且它有效,我可以管理它用于我的服务但是拥有一个对象数组会更好。我究竟做错了什么?
答案 0 :(得分:4)
你应该使用
@RequestBody List<Commit> commits
在您的控制器而不是
@RequestParam(value="commits[]") Commit[] commits
答案 1 :(得分:0)
在我的项目中,我所做的是以下内容(我将尝试使我的解决方案适应您的代码):
$("#buttonCommit").click(function(e){
//Populate the array with selectedCommits values
var myArray = new Array();
$.ajax({
url:'selectedCommits',
method: 'POST',
dataType: 'json',
data:{
branch:branch,
tag:tag,
commits:myArray,
},
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);
}
})
});
通过这种方式并且不使用JS stringify
方法,所有工作都很好
安吉洛
答案 2 :(得分:0)
JS:
$.ajax({
type : "post",
dataType : 'json',
url : 'addAdmin',
data : JSON.stringify(selectedCommits)
})
Controller(注意它只需要一个自定义字符串)。然后它使用 Jackson 手动解析字符串,因为在这种情况下 Spring 不会这样做。 (如果您使用 @ModelAttribute 表单绑定,Spring 只会自动解析。)
@PostMapping("/addAdmin")
public boolean addAdmin(@RequestBody String json) throws Exception {
String decodedJson = java.net.URLDecoder.decode(json, "UTF-8");
ObjectMapper jacksonObjectMapper = new ObjectMapper(); // This is Jackson
List<UserRolesGUIBean> userRolesGUIBeans = jacksonObjectMapper.readValue(
decodedJson, new TypeReference<List<UserRolesGUIBean>>(){});
// Now I have my list of beans populated.
}