将位置标头添加到 Spring MVC 的 POST 响应? [英] add location header to Spring MVC's POST response?

查看:76
本文介绍了将位置标头添加到 Spring MVC 的 POST 响应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆