Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass an array of integer into spring controller?

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

like image 822
user4127 Avatar asked Oct 18 '13 02:10

user4127


People also ask

How do you assign an int array?

To initialize or instantiate an array as we declare it, meaning we assign values as when we create the array, we can use the following shorthand syntax: int[] myArray = {13, 14, 15}; Or, you could generate a stream of values and assign it back to the array: int[] intArray = IntStream.

How do you turn an array of strings into integers?

The string. split() method is used to split the string into various sub-strings. Then, those sub-strings are converted to an integer using the Integer. parseInt() method and store that value integer value to the Integer array.

How do you read an integer array?

Use a char array to read in a string representation of your whole number, then convert each character element of the array into its corresponding numeric value. int d[11]; char stringArray[12];//11 digit characters, + Null terminator.


1 Answers

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;
}
like image 80
mapm Avatar answered Oct 28 '22 03:10

mapm