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

64,051

Solution 1

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.

Solution 2

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

Solution 3

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

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

Solution 4

Fully tested solution

$.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);
    }
}); 

@RequestMapping(value = "/save/", method = RequestMethod.POST)
    public String controllerMethod(@RequestParam(value="myArray[]") List<Integer> myArray){
        System.out.println("My Array"+myArray.get(0));
        return "";
    }

Solution 5

I end up doing this and it works

In js,

var a = [];
a[0] = 1;
a[1] = 2;
a[2] = 3;


$.ajax({
    type : "POST",
    url : "/myurl",
    data : "a="+a,  //multiple array, just add something like "&b="+b ...
    success : function(response) {
       // do something ... 
    },
    error : function(e) {
       alert('Error: ' + e);
    }
}); 

java side, get a class to receive data, using lombok

@Setter @Getter public class MyData { private ArrayList a;
}

then in the controller

@RequestMapping(value = "/repair_info", method = RequestMethod.POST)
public ModelAndView myControl(MyData myData) {
    // get data with myData object
}
Share:
64,051

Related videos on Youtube

Alfred Zhong
Author by

Alfred Zhong

Updated on May 09, 2020

Comments

  • Alfred Zhong
    Alfred Zhong about 4 years

    I would like to pass an array from javascript in web browser to a Spring MVC controller using AJAX

    In javascript, I have

    var a = [];
    a[0] = 1;
    a[1] = 2;
    a[2] = 3;
    
    // how about multiple arrays as well?
    
    $.ajax({
        type : "POST",
        url : "/myurl",
        data : //not sure how to write this, ("a="+a), ?
        success : function(response) {
           // do something ... 
        },
        error : function(e) {
           alert('Error: ' + e);
        }
    }); 
    

    In Java, I would like to create a class to receive data from AJAX, and I create a class to receive data

    package com.amazon.infratool.ui;
    
    import lombok.Getter;
    import lombok.Setter;
    
    
    @Setter @Getter
    public class RepairInfomationParameters {
    //how to write this variable?
        List<String> a = null; // is it something like this?
    }
    

    What is the correct way to do this? Thanks!

  • Alfred Zhong
    Alfred Zhong almost 11 years
    Thanks @vivin, how about multiple arrays? data: {myArray: a, myArray2: b, ...} ?
  • Alfred Zhong
    Alfred Zhong almost 11 years
    should myArray be a string like "myArray"?
  • Vivin Paliath
    Vivin Paliath almost 11 years
    @AlfredZhong I saw that you were using an array of ints, which is why I made it Integer. But there is no reason that you can't make it into String[] or List<String>.
  • Vivin Paliath
    Vivin Paliath almost 11 years
    @AlfredZhong I modified the second example to use ModelAttribute instead of RequestParam. RequestParam is for primitives.
  • Alfred Zhong
    Alfred Zhong almost 11 years
    I got a [object Object] error, I guess it is something related to the data when $ajex converts it to a string under the cover?
  • Vivin Paliath
    Vivin Paliath almost 11 years
    @AlfredZhong You must have some other error in your JavaScript. Are there any more details?
  • Alfred Zhong
    Alfred Zhong almost 11 years
    Thanks a lot for helping. I removed the ModelAttribute annotation and use just string to pass data, like in my own answer, and it works now!
  • jackyesind
    jackyesind almost 11 years
    @VivinPaliath Could you help me on this stackoverflow.com/questions/18102452/…
  • Kayaman
    Kayaman over 8 years
    This seemed to work in our case too, whereas Vivin's answer didn't.
  • Vivin Paliath
    Vivin Paliath almost 8 years
    Looks like it was updated in recent versions on spring. I'll update my answer.
  • Half Blood Prince
    Half Blood Prince almost 8 years
    The key thing was you have to specify [] after variable name like myArray[]. Gosh, ate my half day.