如何正确处理 Spring Data REST 控制器中的请求参数?

how to properly handle request parameters in a Spring Data REST controller?

在我的 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);
        }
    }

当我进行以下操作时 post:

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

我应该更改什么来修复此错误?

但是你没有通过id,这个URL应该是localhost:8080/people/123

注意 - 123 是 id

正如@Parth Solanki 提到的,localhost:8080/people/123 将解决这个问题。但这还不够RESTful。由于它是 post,我鼓励您更改控制器方法和参数中的 URL 映射,以便它将 ID 从 URL 中删除。 或者更确切地说,保留相同的代码并将方法更改为 PUT 而不是 POST。我不会做后者。因为它需要消费者预先知道资源的 ID 及其创建而不是更新已经存在的实体。