Send array of objects via GET request with Angular's $http to Java Spring

感情迁移 提交于 2019-12-24 23:01:33

问题


I have a javascript variable which is an array of MyObjects. I can display this variable to the view with the following code:

        <tr ng-repeat="user in lala.users">
            <td>{{ user.firstName }}</td>
            <td>{{ user.lastName }}</td>
        </tr>

Now I am trying to send this array to the server. I am trying something like:

    lala.send = function() {
        $http({
            method: 'GET',
            url: "http://localhost:8080/server/" + lala.users
        }).then(function successCallback(response) {
            if (response.status == 200) {
                lala.users = response.data
            }
        });
    };

How can I pass this array to a list on the server side? Till now I have something like this.

@RequestMapping(value = "/server/{users}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<List<MyObjects>> transform(@PathVariable("users") String[] users) {
        List<MyObjects> results2 = new ArrayList<>();

        //pass array to a list??

        return new ResponseEntity<>(results2, HttpStatus.OK);
    }

回答1:


You can transform your string and use a delimiter, then parse it on your server side. You can also use HttpPost instead of HttpGet request so you can send JSON String and it is easier to parse.




回答2:


Based on Ranielle's answer I proceeded with HttpPost.

Here is the code:

lala.send = function() {
            $http.post("http://localhost:8080/server", lala.users ) 
            .then(function successCallback(response) {
                if (response.status == 200) {
                   lala.users = response.data
                }
            });
        };

And the Spring side

@RequestMapping(value = "server", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<List<MyObjects> sort( @RequestBody List<MyObjects> query) {
        List<MyObjects> results2 = new ArrayList<>();

        for(MyObjects a : query) {
                System.out.println(a.getFirstName());
        }

        return new ResponseEntity<>(results2, HttpStatus.OK);
    }


来源:https://stackoverflow.com/questions/48633039/send-array-of-objects-via-get-request-with-angulars-http-to-java-spring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!