java - 如何在 Spring mvc 中使用新的 httpstatus 代码进行响应

标签 java rest spring-mvc spring-rest

我正在使用 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) ;;
}

最佳答案

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

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;
    }
};

关于java - 如何在 Spring mvc 中使用新的 httpstatus 代码进行响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35440038/

相关文章:

jvm - Java对象的大小

java - LDAP 术语中的 userDn 和 base 是什么

java - 我在简单的 Spring Security 应用程序中做错了什么

java - 使用 Springs MVC 返回 JSON 数据哪种方式更好以及为什么

java - JGit:如何压缩提交

java - 如何使用作业对象数组? (Jni)

php - REST 风格的 URLS 和 PHP

java - 使用注释修改 REST 参数 - Java EE8

node.js - NodeJS 应用程序构建成功(Heroku),但启动时 Heroku 中出现应用程序错误

java - Autowiring 两个实现相同接口(interface)的 bean - 如何将默认 bean 设置为 Autowiring ?