java - 发送 DELETE 时实现状态 200

标签 java spring rest spring-boot

我想用 Spring Boot 实现 DELETE 请求。我试过这个:

@DeleteMapping("remove/{id}")
    public ResponseEntity<?> remove(@PathVariable String id) {
        return ResponseEntity.ok(transactionNotesService.delete(Long.valueOf(id)))
                .orElseGet(() -> notFound().build());
    }

但我得到 The method ok(T) in the type ResponseEntity is not applicable for the arguments (void)

如何修改代码以在执行 DELETE 时返回代码 200?

最佳答案

根据HTTP Spec你应该总是有一个状态为 200 的 body 。

10.2.1 200 OK

The request has succeeded. The information returned with the response is dependent on the method used in the request, for example:

GET an entity corresponding to the requested resource is sent in the response;

HEAD the entity-header fields corresponding to the requested resource are sent in the response without any message-body;

POST an entity describing or containing the result of the action;

TRACE an entity containing the request message as received by the end server.

您应该改用状态 204(无内容),它不接受正文参数。

10.2.5 204 No Content

The server has fulfilled the request but does not need to return an entity-body, and might want to return updated metainformation. The response MAY include new or updated metainformation in the form of entity-headers, which if present SHOULD be associated with the requested variant.

If the client is a user agent, it SHOULD NOT change its document view from that which caused the request to be sent. This response is primarily intended to allow input for actions to take place without causing a change to the user agent's active document view, although any new or updated metainformation SHOULD be applied to the document currently in the user agent's active view.

The 204 response MUST NOT include a message-body, and thus is always terminated by the first empty line after the header fields.

transactionNotesService.delete(Long.valueOf(id));
return ResponseEntity.noContent().build();
            

关于java - 发送 DELETE 时实现状态 200,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54438313/

相关文章:

java - getBytes() 方法返回未知字节

java - 每 30 分钟后的 Spring cron 表达式

java - Jersey REST WS 错误 : "Missing dependency for method... at parameter at index X"

java - 如何在将每个元素作为值集的列表中添加逗号

带有嵌套对象的 Java Spring FormFactory.form

c++ - C++ 中的动态 JSON 消息;

rest - 无效值:Flutter中只有有效值为0:1

rest - 使用 Spring Boot 和 Java 8 的非阻塞 REST

java - 获取文件路径

java - 如何在 Spring Boot 项目 : 上正确配置 Intellij IDEA 中的 jRebel