Vu Minh Vuong
Vu Minh Vuong

Reputation: 81

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

Upvotes: 7

Views: 49111

Answers (2)

bhavin
bhavin

Reputation: 347

You can't have request body for the GET method. If you want to pass username and password as part of request body then change RequestMethod type to POST/PUT.

If you want to use GET only then you will have to pass username and password as either path variables or request/query parameters - which is not best practice.

I would recommend changing RequestMethod and pass username & password as request body.

Upvotes: -3

mhasan
mhasan

Reputation: 3709

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

Upvotes: 22

Related Questions