Pass array data from javascript in browser to spring mvc controller using ajax Pass array data from javascript in browser to spring mvc controller using ajax arrays arrays

Pass array data from javascript in browser to spring mvc controller using ajax


You can do this from the JavaScript side:

$.ajax({    type : "POST",    url : "/myurl",    data : {        myArray: a //notice that "myArray" matches the value for @RequestParam                   //on the Java side    },    success : function(response) {       // do something ...     },    error : function(e) {       alert('Error: ' + e);    }}); 

Then on the Java side (in Spring 3), assuming that this method is mapped by /myurl:

public String controllerMethod(@RequestParam(value="myArray[]") Integer[] myArray){    ....}

I believe the following will also work:

public String controllerMethod(@RequestParam(value="myArray[]") List<Integer> myArray){    ....}

Spring is smart enough to figure out how to do the binding.

For multiple arrays, you might want to just have a command object:

public class MyData {    private List<Integer> firstArray;    private List<Integer> secondArray;    private List<Integer> thirdArray;    ...    ...}

Then on the JavaScript side:

$.ajax({    type : "POST",    url : "/myurl",    data : {                    myData: {           "firstArray": firstArray,           "secondArray": secondArray,           "thirdArray": thirdArray        }                },    success : function(response) {       // do something ...     },    error : function(e) {       alert('Error: ' + e);    }}); 

On the Java side, you can bind using @ModelAttribute:

public String controllerMethod(@ModelAttribute(value="myData") MyData myData) throws ParseException {    ....}

EDIT

Changed the @RequestParam annotation to use myArray[] instead of just myArray, since this change appears to have been made in Spring after this answer was first posted.


It is very simple passing such data to the Spring MVC controller, when you have in mind that data is being parsed from string. So if you want to get an array/list in the controller - pass a stringified version of the array:

public String method(        @RequestParam(value = "stringParam") String stringParam,        @RequestParam(value = "arrayParam") List<String> arrayParam) {    ...}

and the corresponding javascript with jQuery would be like:

$.post("/urlToControllerMethod",    {        "stringParam" : "test",        "arrayParam" : [1, 2, 3, "test"].toString()    });

Note: the parameter type

List<String> arrayParam

could be as well replaced with the array equivalent

String[] arrayParam


Vivin Paliath doesn't work unless you use myArray[]

public String controllerMethod(@RequestParam(value="myArray[]") Integer[] myArray){    ...}