Search code examples
angularjsspringrestspring-restcontroller

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

Solution

  • 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.