@RequestBody 和@RequestParam 都不起作用

neither @RequestBody nor @RequestParam work

我想在 spring 中进行 PUT 调用。

这是我的控制器代码:

@RequestMapping(value = "/magic", method = RequestMethod.PUT)
    TodoDTO magic(@RequestBody String id){
        return service.magic(id);
    }

因为我想在调用中传递一个 id 字符串。

问题是,我收到了这个

{
  "timestamp": 1486644310464,
  "status": 500,
  "error": "Internal Server Error",
  "exception": "java.lang.NullPointerException",
  "message": "{\n\t\"id\":\"589c5e322abb5f28631ef2cc\"\n}",
  "path": "/api/todo/magic"
}

如果我像这样更改代码:

@RequestMapping(value = "/magic", method = RequestMethod.PUT)
    TodoDTO magic(@RequestParam(value = "id") String id){
        return service.magic(id);
    }

我收到了

{
  "timestamp": 1486644539977,
  "status": 400,
  "error": "Bad Request",
  "exception": "org.springframework.web.bind.MissingServletRequestParameterException",
  "message": "Required String parameter 'id' is not present",
  "path": "/api/todo/magic"
}

我打了同样的电话,PUT 在 link http://localhost:8080/api/todo/magic 与 body

{
    "id":"589c5e322abb5f28631ef2cc"
}

这是我数据库中一个 object 的 ID。

我的问题是,我怎样才能实现我的目标?如果我在 link 中传递参数,比如 api/todo/magic/589c5e322abb5f28631ef2cc,使用 @PathVariable,它可以工作

创建您自己的自定义 class 如下所示

Class Request
{
private String id;
//getter and setter
}

并将方法更改为

@RequestMapping(value = "/magic", method = RequestMethod.PUT)
    TodoDTO magic(@RequestBody Request request){
        return service.magic(request.getId());
    }

您也可以在 url 中使用 id 并在方法签名中使用 @Pathvariable

@RequestMapping(value = "/magic/{id}", method = RequestMethod.PUT)
        TodoDTO magic(@PathVariable String id){
            return service.magic(request.getId());
        }

当您使用 @RequestBody String id 时,它只需要一个字符串:

"589c5e322abb5f28631ef2cc"

如果你想发送一个带有id字段的对象,比如

{
    "id":"589c5e322abb5f28631ef2cc"
}

您应该创建一个带有 id 字段的 class 并修改方法的签名以获得此 class 而不是 String

虽然按照其他答案中的建议创建包装器 class 会起作用,但我认为可以避免这种开销并简单地使用 Map。

@RequestMapping(value = "/magic", method = RequestMethod.PUT)
    TodoDTO magic(@RequestBody Map<String, String> data){
        return service.magic(data.get("id");
}