【问题标题】:How to respond with new httpstatus code in Spring mvc如何在 Spring mvc 中使用新的 httpstatus 代码进行响应
【发布时间】:2016-05-28 04:10:02
【问题描述】:

我正在使用 spring MVC 来创建 Rest Web 服务。并想发送一个 213 代码状态作为响应。但是该代码在 org.springframework.http.HttpStatus 类中不存在,并且 ResponseEntity(T body, HttpStatus statusCode) 类接受 HttpStatus 类型。 我们如何处理发送这个 httpStatus 代码? 这是伪代码:

 public ResponseEntity<?> getEvents() {
   //1. call Service 1
   // 2. use result of service 1 to call service 2

   // 3. use result of service 2 to call service 3

   // 4. create result and map it in DTO object

   if( result of service 1 is empty) return empty result with status 213
   if( result of service 2 is empty) return empty result with status 214

    return new ResponseEntity(result.getBody(), status code) ;;
}

【问题讨论】:

  • 您可以发布一些代码示例,以显示您正在尝试做什么吗?在 Spring 中有许多不同的方法可以从控制器返回一些东西。所以示例代码将帮助我更好地回答你的代码风格。
  • 您试图通过使用非标准 HTTP 状态代码来完成什么? 200s 中的代码通常表示请求处理成功。您是否尝试指出/处理某种边缘成功案例?
  • 非常有效的问题。这对于实现 REST API 非常有用。有人能解决这个限制吗?

标签: java rest spring-mvc spring-rest


【解决方案1】:

我想出了一个相当老套但仍然非常简单易行的解决方法:

new ResponseEntity<String>(
    "my body", 
    null, 
    HttpStatus.I_AM_A_TEAPOT /*status doesn't matter, just has to be anything*/
) {
    @Override
    public int getStatusCodeValue() {
        return MY_CUSTOM_RESPONSE_CODE;
    }
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-25
    • 2015-07-14
    • 2020-01-06
    • 2017-12-30
    • 2022-12-03
    • 1970-01-01
    • 1970-01-01
    • 2015-11-26
    相关资源
    最近更新 更多