【问题标题】:Spring is refusing to send a ResponseEntity but does not throw exceptionsSpring 拒绝发送 ResponseEntity 但不抛出异常
【发布时间】:2018-06-24 04:53:30
【问题描述】:

我的 POJO/数据模型:

public class CanResendResponse {
    @JsonProperty(value = "canResend")
    @NotEmpty
    public Boolean canResend;

    // getters, setters & ctors
}

我的 Spring Boot 控制器和方法:

@RestController
@RequestMapping("v1/data/fizzes")
class FizzResource {
    @GetMapping(value = "{fizzId}/canResend")
    public void canResendVerifications(@PathVariable(value = "fizzId") String fizzId) {
        Fizz fizz = fizzRepository.findById(fizzId);
        Boolean canResend;

        System.out.println("Fizz name:" + fizz.getName());

        if(fizz.canResend()) {
            canResend = Boolean.TRUE;
        } else {
            canResend = Boolean.FALSE;
        }

        return new ResponseEntity<CanResendResponse>(new CanResendResponse(canResend), HttpStatus.OK);
    }
}

我的 curl 命令:

curl -H "Content-Type: application/json" -X GET https://localhost:9200/v1/data/fizzes12345/canResend

当我运行 curl 命令时,我在服务器端看不到任何异常/错误,并且 curl 完成时没有错误,但我没有看到预期的 HTTP 响应实体,例如:

{
  "canResend" : "true"
}

但是我确实在 STDOUT 中看到了 Fizz name: Joe 消息。

我已经在浏览器中确认了相同的行为(我将https://localhost:9200/v1/data/fizzes12345/canResend 打入浏览器并且响应/页面为空。 有什么想法可以解决这个问题吗?

【问题讨论】:

  • 你永远不会从方法中返回任何东西
  • 剪切粘贴错误 - 请查看我的更新@shazin
  • 方法签名无效时如何返回?在 Stackoverflow 中发布之前,你甚至会编译这个吗?
  • 嗨@shazin 这实际上是用Groovy 编写的,我正在用Java 重新编写我的代码,所以我可以将它粘贴到这里。 Groovy 允许这样做,而 Java 不允许。但由于我知道这是对 Spring 的错误利用(就我而言),我不想将人们与 Groovy 的东西混淆。

标签: java rest spring-mvc spring-boot


【解决方案1】:

您的方法具有 VOID 返回类型。试试这个:

@GetMapping(value = "{fizzId}/canResend")
public ResponseEntity canResendVerifications(@PathVariable(value = "fizzId") String fizzId) {
    Your method code goes here...
}

【讨论】:

    【解决方案2】:

    改变

    public void canResendVerifications(@PathVariable(value = "fizzId") String fizzId) {
    

    public ResponseEntity<> canResendVerifications(@PathVariable(value = "fizzId") String fizzId) {
    

    ...并确保您return 那个ResponseEntity

    【讨论】:

      猜你喜欢
      • 2012-09-11
      • 2013-05-24
      • 1970-01-01
      • 1970-01-01
      • 2015-10-11
      • 1970-01-01
      • 2020-02-02
      • 2020-10-28
      • 2012-10-19
      相关资源
      最近更新 更多