更新时间:2023-12-03 21:23:04
中演示了这个确切的场景使用 Spring 指南构建 REST 服务.
持久化新实体后,您可以在控制器中使用以下内容:
Once you have persisted your new entity, in your controller you can use the below:
URI location = ServletUriComponentsBuilder
.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(newEntity.getId())
.toUri();
然后您可以使用 ResponseEntity 如下:
You can then add this to your response using ResponseEntity as below:
ResponseEntity.created(location).build()
或
ResponseEntity.status(CREATED).header(HttpHeaders.LOCATION, location).build()
后者需要一个字符串,因此您可以在 uri 构建器上使用 toUriString()
而不是 toUri()
.
The latter expects a string so you can use toUriString()
on the uri builder instead of toUri()
.