错误:缺少所需的请求正文

问题描述:

我正在尝试Spring框架. 我有RestController和功能:

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);
    }

和代码angularJS

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";
        });
    }

当我运行它时.

错误消息:

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)

请帮我修复它,

此代码中包含问题.

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

同一方法中不能有多个@RequestBody,因为它可以绑定到 仅单个对象(身体只能被消耗一次).

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

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

一种方法是将它们全部嵌入到单个JSON中,如下所示

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

方法2:

ArgumentResolver