Reputation: 2447
script Array
of int
and I wish to pass into Spring Controller
. but I keep getting
400 bad request.
if my js array
is
array = [1,2,3,4]
array -> 400 bad request
JSON.Stringify(array) -> I will get [1,2,3,4]
$.ajax({//jquery ajax
data:{"images": array},
dataType:'json',
type:"post",
url:"hellomotto"
....
})
when I loop the string List
.. the first element will be '[1'
@RequestMapping(value = "/hellomotto", method = Request.POST)
public void hellomotto(@RequestParam("images") List<String> images){
sysout(images); -> I will get [1,2,3,4]
}
public void
May I know how can I do this properly? I have tried different combination
Upvotes: 5
Views: 25300
Reputation: 1395
The following is a working example:
Javascript:
$('#btn_confirm').click(function (e) {
e.preventDefault(); // do not submit the form
// prepare the array
var data = table.rows('.selected').data();
var ids = [];
for(var i = 0; i < data.length; i++) {
ids.push(Number(data[i][0]));
}
$.ajax({
type: "POST",
url: "?confirm",
data: JSON.stringify(ids),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){
alert(data);
},
failure: function(errMsg) {
alert(errMsg);
}
});
});
Controller:
@RequestMapping(params = "confirm", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody int confirm(@RequestBody Long[] ids) {
// code to handle request
return ids.length;
}
Upvotes: 7
Reputation: 6118
I think you wantAjax call,through ajax, you are sending List of Integers so in spring your controller will be
@RequestMapping(value = "/hellomotto", method = Request.POST)
@ResponseBody
public void hellomotto(@RequestParam("images") List<Integer> images){
sysout(images); -> I will get [1,2,3,4]
}
*@ResponseBody is missing in Your Code
Upvotes: 0
Reputation: 2740
@RequestParam is used to bind request parameters, so if you do something like
@RequestMapping(value = "/hellomotto", method = Request.POST)
public void hellomotto(@RequestParam("image") String image){
...
}
and you do post to /hellomotto?image=test, the image variable in hellomotto method will contain "test"
What you want to do is to parse Request body , so you should you should use @RequestBody annotation :
http://docs.spring.io/spring/docs/3.0.x/reference/mvc.html#mvc-ann-requestbody
it is using jackson labrary (so you will have to include it as your dependency) to parse json object into java object.
Upvotes: 0