我正在使用 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;
}
};
我是一名优秀的程序员,十分优秀!