简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM