user12665947
user12665947

Reputation:

How to send a javascript array to Spring MVC controller

I am trying to send a javascript array to Spring MVC controller..But I am getting null value..

My javascript Code:

for (var n = 1; n < rowCount; n++) {
            cells = rows[n].cells;
            data.push([
                cells[0].firstElementChild.checked,
                cells[1].firstElementChild.value,
                cells[2].firstElementChild.value,
                cells[3].firstElementChild.value,
                cells[4].firstElementChild.value
           ]);
}

$.ajax({
        url: 'addDetails.html',
        type:"POST",
        data:
{promo : data}

My Spring MVC Controller Request Mapping:

@RequestMapping("/addDetails")
    public @ResponseBody void addEntity(
            @RequestParam(value="promo") List<String> promo) throws IOException {

I am not getting any value in Requestmapping for promo.Kindly help Me..Thank You!

Upvotes: 0

Views: 188

Answers (1)

Mustahsan
Mustahsan

Reputation: 3862

The POST Body can be recieved in RequestBody not in RequestParam, and secondly if you pass your array like {promo: data} it will be converted to HashMap or some POJO Object not the Array List, so directly pass the array like:

$.ajax({
        url: 'addDetails.html',
        type:"POST",
        data:data

and make your controller like:

@RequestMapping("/addDetails", method = {RequestMethod.POST})
public @ResponseBody void addEntity(
            @RequestBody List<String> promo) throws IOException {

UPDATE For More Data you can make a POJO Class:

public class MyData{
    private String lname;
    private String lstate;
    private String lrta;
    private String lse;
    private List<String> promo;

   ... Getters and Setters
}

and your controller should be:

@RequestMapping("/addDetails", method = {RequestMethod.POST})
public @ResponseBody void addEntity(
                @RequestBody MyData myData) throws IOException {

Upvotes: 1

Related Questions