【问题标题】:what's the best way to return an empty ResponseEntity with Spring? [duplicate]用 Spring 返回一个空的 ResponseEntity 的最佳方法是什么? [复制]
【发布时间】:2020-05-16 03:07:04
【问题描述】:

我想知道如果我返回一个空的 ResponseEntity,我的控制器的最佳返回类型是什么。
例如,如果我想返回 204 - 没有使用 ResponseEntity.noContent().build() 的内容,我的函数的返回应该是 ResponseEntity<?>ResponseEntity<Void> 还是只是 ResponseEntity

【问题讨论】:

  • 放置 ResponseEntity 因为你不返回正文
  • 它并没有真正告诉我这三个命题中哪个是最好的
  • “它并没有真正告诉我这三个命题中哪个是最好的”——因为“最好”是一个见仁见智的问题。只针对您易于阅读和理解的内容,因为它会使以后的维护更容易。
  • 您的休息控制器方法应该返回 ResponseEntity。然后,您可以添加所需的任何标题和状态。例如:HttpHeaders headers = new HttpHeaders(); headers.add(HttpHeaders.LOCATION, baseUri + "/api/contacts/" + id);最后:返回新的 ResponseEntity(null, headers, HttpStatus.FOUND)

标签: java spring-boot spring-mvc


【解决方案1】:

我更喜欢ResponseEntity.noContent().build(),它清楚地说明了它在做什么,返回类型可以只是ResponseEntity

我个人喜欢没有“Void”的返回类型对我来说看起来很干净。

春季文档如下所述

public ResponseEntity(HttpStatus statusCode)

使用给定的状态码创建一个新的 ResponseEntity,并且没有正文 也不是标题。

参数: statusCode - 状态码

https://docs.spring.io/spring/docs/3.0.x/javadoc-api/org/springframework/http/ResponseEntity.html#ResponseEntity(org.springframework.http.HttpStatus)

【讨论】:

  • 但是我应该把什么作为返回类型?
  • 谢谢,但这真的是最好的解决方案吗?
【解决方案2】:
ResponseEntity<Void> with HttpStatus.NO_CONTENT

【讨论】:

  • 这真的是最好的解决方案吗?如果是,为什么?
  • 在这种情况下没有最佳解决方案, ResponseEntity 和 ResponseEntity 都有效。我会使用 ResponseEntity 因为它指示返回的内容。
猜你喜欢
  • 2016-11-02
  • 2011-09-10
  • 2019-12-02
  • 1970-01-01
  • 2022-01-08
  • 1970-01-01
  • 2010-09-16
  • 2012-10-23
  • 1970-01-01
相关资源
最近更新 更多