[英]neither @RequestBody nor @RequestParam work
我想在春季打电话。
这是我的控制器代码:
@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与正文链接http:// localhost:8080 / api / todo / magic
{
"id":"589c5e322abb5f28631ef2cc"
}
这是我的数据库中一个对象的ID。
我的问题是,我如何实现我的目标? 如果我通过@PathVariable在链接中传递参数,例如api / todo / magic / 589c5e322abb5f28631ef2cc
创建您自己的自定义类,如下所示
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
字段的类并修改方法的签名以获取该类,而不是String
。
虽然按照其他答案中的建议创建包装类将起作用,但我认为有可能避免这种开销并仅使用Map。
@RequestMapping(value = "/magic", method = RequestMethod.PUT)
TodoDTO magic(@RequestBody Map<String, String> data){
return service.magic(data.get("id");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.