Avr*_*Pop 0 java spring spring-mvc spring-restcontroller
我想在春天做一个PUT电话.
这是我的控制器代码:
@RequestMapping(value = "/magic", method = RequestMethod.PUT)
TodoDTO magic(@RequestBody String id){
return service.magic(id);
}
Run Code Online (Sandbox Code Playgroud)
因为我想在通话中传递一个id字符串.
问题是,我收到了这个
{
"timestamp": 1486644310464,
"status": 500,
"error": "Internal Server Error",
"exception": "java.lang.NullPointerException",
"message": "{\n\t\"id\":\"589c5e322abb5f28631ef2cc\"\n}",
"path": "/api/todo/magic"
}
Run Code Online (Sandbox Code Playgroud)
如果我改变这样的代码:
@RequestMapping(value = "/magic", method = RequestMethod.PUT)
TodoDTO magic(@RequestParam(value = "id") String id){
return service.magic(id);
}
Run Code Online (Sandbox Code Playgroud)
我收到
{
"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"
}
Run Code Online (Sandbox Code Playgroud)
我做了同样的电话,一个PUT在链接http:// localhost:8080/api/todo/magic with body
{
"id":"589c5e322abb5f28631ef2cc"
}
Run Code Online (Sandbox Code Playgroud)
这是我的数据库中一个对象的id.
我的问题是,我怎样才能实现目标?如果我通过链接传递参数,如api/todo/magic/589c5e322abb5f28631ef2cc,@ PathVariable,它的工作原理
创建您自己的自定义类,如下所示
Class Request
{
private String id;
//getter and setter
}
Run Code Online (Sandbox Code Playgroud)
并改变方法
@RequestMapping(value = "/magic", method = RequestMethod.PUT)
TodoDTO magic(@RequestBody Request request){
return service.magic(request.getId());
}
Run Code Online (Sandbox Code Playgroud)
您也可以在url中使用id并在方法签名中使用@Pathvariable
@RequestMapping(value = "/magic/{id}", method = RequestMethod.PUT)
TodoDTO magic(@PathVariable String id){
return service.magic(request.getId());
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
563 次 |
| 最近记录: |