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

时间:2016-02-16 18:11:51

标签: 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) ;;
}

1 个答案:

答案 0 :(得分:0)

我想出了一个相当棘手的方法,但是仍然非常简单易行:

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