Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bug: Required request body is missing

I'm trying spring framework. I have RestController and function:

@RequestMapping(value="/changePass", method=RequestMethod.POST)
    public Message changePassword(@RequestBody String id, @RequestBody String oldPass, 
                                                        @RequestBody String newPass){
        int index = Integer.parseInt(id);
        System.out.println(id+" "+oldPass+" "+newPass);
        return userService.changePassword(index, oldPass, newPass);
    }

and code angularJS

$scope.changePass = function(){//changePass
        $scope.data = {
            id: $scope.userId,
            oldPass:$scope.currentPassword,
            newPass:$scope.newPassword
        }
        $http.post("http://localhost:8080/user/changePass/", $scope.data).
            success(function(data, status, headers, config){
                if(date.state){
                    $scope.msg="Change password seccussful!";
                } else {
                    $scope.msg=date.msg;
                }
        })
        .error(function(data, status, headers, config){
            $scope.msg="TOO FAIL";
        });
    }

and when i run it.

Error Message :

Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public com.csc.mfs.messages.Message com.csc.mfs.controller.UserController.changePassword(java.lang.String,java.lang.String,java.lang.String)

Help me fix it, pls...

like image 580
Vu Minh Vuong Avatar asked Mar 11 '17 15:03

Vu Minh Vuong


1 Answers

Issue is in this code.

@RequestBody String id, @RequestBody String oldPass, 
                                                        @RequestBody String newPass

You cannot have multiple @RequestBody in same method,as it can bind to a single object only (the body can be consumed only once).

APPROACH 1:

Remedy to that issue create one object that will capture all the relevant data, and than create the objects you have in the arguments.

One way for you is to have them all embedded in a single JSON as below

{id:"123", oldPass:"abc", newPass:"xyz"}

And have your controller as single parameter as below

 public Message changePassword(@RequestBody String jsonStr){

        JSONObject jObject = new JSONObject(jsonStr);
.......
 }

APPROACH 2:

Create a custom implementation of your own for ArgumentResolver

like image 140
mhasan Avatar answered Oct 21 '22 00:10

mhasan