java - Spring REST - 当资源尚不存在时正确的 PUT 功能

标签 java spring rest spring-mvc put

我正在使用 Spring 构建 REST API 并实现 PUT 功能。我正在尝试处理客户端尝试 PUT 到资源尚不存在的 uri 的场景。在这种情况下,根据 PUT 规范,应使用该 ID 创建新资源。但是,由于我使用的 ID 生成策略 (@GenerateValue(strategy = GenerationType.IDENTITY)),我无法创建 ID 不按顺序排列的资源。数据库必须使用下一个可用值。然而,根据 PUT 上的 w3 规范...

If the Request-URI does not point to an existing resource, and that URI is capable of being defined as a new resource by the requesting user agent, the origin server can create the resource with that URI.

If the server desires that the request be applied to a different URI, it MUST send a 301 (Moved Permanently) response; the user agent MAY then make its own decision regarding whether or not to redirect the request.

在这种情况下,我这两件事都做不到。由于 ID 生成限制,我无法在现有 URI 上创建新资源,并且无法发送 301 Moved Permanently 响应,因为根据 How do I know the id before saving an object in jpa在实际持久化对象之前不可能知道序列中的下一个 ID。因此,我无法告诉客户端要重定向到哪个 URI 才能正确创建新资源。

我想这个问题已经解决了很多次,因为它是标准的 PUT 功能,但我很难找到任何其他尝试过这样做的人。似乎大多数人只是忽略了 PUT 的“创建新资源”部分,而只是将其用作更新。

我想要做的就是继续创建新资源,然后发送 301 Moved Permanently 将客户端重定向到所创建资源的真实位置 - 但正如我们在上面看到的,这违反了 PUT 的定义.

有没有一种 spring-y 的方法来解决这个问题?或者问题是否尚未解决,而真正的标准做法是根本不允许通过 PUT 创建新资源?

最佳答案

如果由于请求错误导致服务器无法处理请求,则返回 400。

400 Bad Request - The server cannot or will not process the request due to an apparent client error (e.g., malformed request syntax, size too large, invalid request message framing, or deceptive request routing).

关于java - Spring REST - 当资源尚不存在时正确的 PUT 功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59849039/

相关文章:

java - 如何执行jar可执行文件并接收返回值

java - 自定义 AlertDialog 更改/覆盖状态栏颜色,那么我该如何解决这个问题?

java - 如何获取 XmlType 的字符串表示形式?

java - 将 Vector3 缓动到新位置

eclipse - 无法实例化 [org.springframework.web.context.support.XmlWebApplicationContext]

java - 使用 REST Api 删除 OTDS 用户 - 无法删除同步对象

spring - CommonsMultipartResolver setMaxUploadSize 限制文件大小还是请求大小?

java - Spring 与 Guice 实例化对象

rest - 使用 go API 在 blobstore 上上传文件

java - 如何将投影应用于 Spring Data REST 查询方法资源?