0

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!

1 Answer 1

1

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 {
Sign up to request clarification or add additional context in comments.

3 Comments

I have other values also to get it to the controller.$.ajax({ url: 'addDetails.html', type:"POST", data:{ lname:lname, lname : document.getElementById('lname').value, lstate : document.getElementById('lstate').value, lrta : document.getElementById('lrta').value, lse : document.getElementById('lse').value, promo : data },
if you want all of them to send in one request you can make a Class and then pass that object in controller and it will be fine
@PUSHPARAJN i have updated my answer please have a look