Steve Green
Steve Green

Reputation: 79

Passing json as body and another object as parameter to spring controller

I'm passing back a list of objects as json to my spring controller, but I also need to pass it some customer details too such as firstname, lastname, address, payment type - so I thought I create a POJO for this and pass this as a request param but no luck.

Spring controller:

  @RequestMapping(value = "/addstock", method = RequestMethod.POST)
    public @ResponseBody
    String addPersons(@RequestBody StockList stock, @RequestParam(name="details") AddDetails details) throws ParseException, IOException

Pojo is AddDetails which has the getter/setter etc using lombok. I try to pass as follows in my javascript:

 function sendData() {
            var stocks = JSON.stringify({'stocks': model.stock()});
            var obj = { "firstname":"Steve", "lastname":"Green"};
            obj = JSON.stringify({'details':obj});
            $.ajax({
                url:"/addstock?details="+obj,
                type: 'POST',
                data:  stocks,
                dataType: "html",
                contentType: 'application/json',
                mimeType: 'application/json',
                success: function(data){
                    console.log(data);
                    return false;
                }
            });
        }

But obviously I cannot pass an object across to the details param. Is it possible another way?

Many thanks

*** UPDATE ***

Sorted this now, I basically created another pojo for customer details which is added to the stock json object:

Example:

function sendData() {
            var adddetails = {firstname:"steve",lastname: "jack",add1:"6 redby lane",add2:"brixon",add3:"",city:"manchester",postcode:"b3434",tel:"0090909090"};
            var stocks = JSON.stringify({'details':adddetails,'stocks': model.stock()});
            $.ajax({
                url:"/addstock",
                type: 'POST',
                data:  stocks,
                dataType: "html",
                contentType: 'application/json',
                mimeType: 'application/json',
                success: function(data){
                    console.log(data);
                    return false;
                }
            });
            return false;
        }


@Getter
@Setter
public class AddDetails {
    private String firstname, lastname,add1,add2,add3,postcode,tel;
}

@Getter
@Setter
public class StockList {
    AddDetails details;
    List<Stock> stocks;
}

  @RequestMapping(value = "/addstock", method = RequestMethod.POST)
    public @ResponseBody
    String addPersons(@RequestBody StockList stock) throws ParseException, IOException {
        try {

            // perform add operation
            stock.getStocks().forEach(s->System.out.println(s));
            return "Successfully added stock.";
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
        return "Error";
    }

Upvotes: 0

Views: 1147

Answers (1)

Santi Wagner
Santi Wagner

Reputation: 318

There are several ways to do this. The first option is to remove the @RequestParam annotation and Spring will automatically bind the parameters in the query string to your POJO. However, in your code you are appending a JSON representation to the URL, and that's not possible. This is the correct syntax you should be using for the AddDetails fields:

/addstock?firstname=value1&lastname=value2

Another possible solution is to define a DTO that contains both the list of stocks and an AddDetails object and pass it as body of the request. For example:

public class StockListDTO{
    
    List<Stock> stocks;

    AddDetails details;

    //Getter and setters or use Lombok

}

And your method signature:

 @RequestMapping(value = "/addstock", method = RequestMethod.POST)
    public @ResponseBody
    String addPersons(@RequestBody StockListDTO body) throws ParseException, IOException

Upvotes: 1

Related Questions