在我的Spring Data REST应用程序中,我有以下控制器:
@RestController
@RequestMapping("/people")
public class PersonController {
@RequestMapping(value = "/**", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> savePerson(@RequestBody Person person, UriComponentsBuilder b, @RequestParam Map<String, ?> id) {
UriComponents uriComponents =
b.path("/people/{id}").buildAndExpand(id);
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setLocation(uriComponents.toUri());
responseHeaders.set("MyResponseHeader", "MyValue");
return new ResponseEntity<String>("Hello World\n\n", responseHeaders, HttpStatus.CREATED);
}
}
当我发表以下帖子时:
curl -i -X POST -H "Content-Type:application/json" -d '{ "firstName" : "Frodo", "lastName" : "Baggins" }' http://localhost:8080/people
我收到此错误:
{"timestamp":1476418616900,"status":500,"error":"Internal Server Error","exception":"java.lang.IllegalArgumentException","message":"Map has no value for 'id'","path":"/people"}
我应该更改什么来修复此错误?
答案 0 :(得分:1)
但您还没有通过id
,此网址应为localhost:8080/people/123
注意 - 123为id
答案 1 :(得分:0)
@Parth Solanki提到localhost:8080 / people / 123将解决这个问题。但这还不够RESTful。由于这是一篇帖子,我建议您更改控制器方法和参数中的URL映射,以便从URL中删除ID。 或者更确切地说保持相同的代码并将方法更改为PUT而不是POST。我不会做后者。因为它需要消费者预先知道资源的id及其创建而不是已经存在的实体的更新。