gpt4 book ai didi

java - Spring @ResponseStatus 返回空响应

转载 作者:塔克拉玛干 更新时间:2023-11-01 23:02:54 29 4
gpt4 key购买 nike

在我的 Spring API 中,我想使用 Spring 的注解 @ResponseStatus 来处理创建、放置和删除等操作的响应。每个端点都正常工作,但它们总是返回空响应。

为什么带注释的端点的响应为空?

Controller :

import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.http.HttpStatus;

@RestController
@RequestMapping(value = "/v1/portfolios")
public class PortfolioController {

@RequestMapping(method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
public void create(@RequestBody Portfolio resource) {
repo.save(resource);
}

@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
@ResponseStatus(HttpStatus.OK)
public void delete(@PathVariable("id") String id) {
repo.removeById(id);
}

}

最佳答案

Why response from annotated endpoints is empty?

因为您的方法返回 void (意味着没有 body )。状态码 - 它不是 body 。

你可以试试这个来返回带有消息显式的响应:

@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
public ResponseEntity<String> delete(@PathVariable("id") String id) {
repo.removeById(id);
return new ResponseEntity<>("Your message here", HttpStatus.OK);
}

而不是 ResponseEntity<String>你可以把ResponseEntity<YourCustomObject>然后返回 new ResponseEntity<>(yourCustomObject instance, HttpStatus.OK);响应时会转成JSON。

你也可以这样做:

@ResponseStatus(value = HttpStatus.OK, reason = "Some reason")

在这种情况下,您将返回如下内容:

{
"timestamp": 1504007793776,
"status": 200,
"error": "OK",
"message": "Some reason",
"path": "/yourPath"
}

关于java - Spring @ResponseStatus 返回空响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45936441/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com