gig*_*gi2 3 java rest post http spring-mvc
我的Spring boot 1.4应用程序具有此POST方法来创建资源。根据要求,它应该吐出一个位置标头,以指定新创建的资源的URL(https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html)。我只是想知道是否有比手动构造URL并将其添加到响应中更好的方法。
任何帮助/线索深表感谢
使用Spring指南构建REST服务中演示了此确切方案。
保留新实体后,可以在控制器中使用以下内容:
URI location = ServletUriComponentsBuilder
.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(newEntity.getId())
.toUri();
Run Code Online (Sandbox Code Playgroud)
然后可以使用ResponseEntity将其添加到您的响应中,如下所示:
ResponseEntity.created(location).build()
Run Code Online (Sandbox Code Playgroud)
要么
ResponseEntity.status(CREATED).header(HttpHeaders.LOCATION, location).build()
Run Code Online (Sandbox Code Playgroud)
后者需要一个字符串,因此您可以toUriString()在uri构建器上使用而不是toUri()。
| 归档时间: |
|
| 查看次数: |
2072 次 |
| 最近记录: |