将位置标头添加到 Spring MVC 的 POST 响应? [英] add location header to Spring MVC's POST response?
问题描述
我的 Spring boot 1.4 应用程序有这个 POST 方法来创建资源.作为一项要求,它应该吐出一个位置标头,指定新创建的资源的 URL (https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html).我只是想知道是否有比手动构建 URL 并将其添加到响应中更好的方法.
My Spring boot 1.4 application has this POST method to create a resource. As a requirement, it should spit a location header specifying the URL of the newly created resource (https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html). I am just wondering if there is any good way to do it than manually constructing the URL and adding it to the response.
非常感谢任何帮助/线索
Any helps/clues are deeply appreciated
推荐答案
中演示了这个确切的场景使用 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()
.
这篇关于将位置标头添加到 Spring MVC 的 POST 响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!