iwsnmw
iwsnmw

Reputation: 642

Sending multiple data objects (angular - spring rest)

The below code works fine but I couldn't figure out how to handle the request in the case of sending two data objects.

        //angular 
        $scope.data = //item object
        $http({
            method : 'POST',
            url : '/items',
            data : $scope.data,
            headers : {
                'Content-Type' : 'application/json'
            }
        }).success(function(data) {
        //...
        });
       //java rest
       @RequestMapping(value="/items", method=RequestMethod.POST)
       public ResponseEntity<?> createIslem(@RequestBody Item item){ 
       //....
       }

How should my java controller method signature be to handle the request below?

        //angular 
        $scope.data = //item object
        $http({
            method : 'POST',
            url : '/items',
            //data1 is of type Item and data2 is of type AnotherObject
            data : {data1: $scope.data1, data2: $scope.data2}
            headers : {
                'Content-Type' : 'application/json'
            }
        }).success(function(data) {
        //...
        });

Upvotes: 1

Views: 2553

Answers (1)

JB Nizet
JB Nizet

Reputation: 691735

Well, you should have a class like the following:

public class Command {
    private Item data1;
    private AnotherObject data2;
    // getters and setters omitted for brevity
}

and the method should be declared as

public ResponseEntity<?> createIslem(@RequestBody Command command)

So that the Java object structure matches with the structure of the JavaScript object you're sending.

Upvotes: 2

Related Questions