Spring在没有ResponseEntity的情况下管理自定义DTO类的http状态

时间:2021-07-04 19:44:53

标签: spring spring-boot

public class ApiResponse {
        long timestamp;
        int status;
        String error;
        String message;
        String path;

        public ApiResponse(HttpStatus status, String message) {
         super();
         this.status = status.value();
         this.message = message;
        }

    }

我有这个类,我想做的是根据 ApiResponse 对象的状态值设置响应状态

return new ApiResponse(HttpStatus.CREATED, "Success");

我希望响应状态为 201。

这样的事情有可能吗?

我知道有 ResponseEntity 类,但我想在不使用这个类的情况下处理它。

1 个答案:

答案 0 :(得分:1)

使用ResponseBodyAdvice接口统一处理响应。

@RestControllerAdvice
public class TransformStatusBodyAdvice implements ResponseBodyAdvice<ApiResponse> {

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        // check return type is ApiResponse
        return returnType.getParameterType().isAssignableFrom(ApiResponse.class);
    }

    @Override
    public ApiResponse beforeBodyWrite(ApiResponse body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (body != null) {
            // change something if you want
            // set the response status code
            response.setStatusCode(HttpStatus.valueOf(body.getStatus()));
        }
        return body;
    }
}

测试控制器

@RestController
@RequestMapping("/test")
public class TestController {

    @PostMapping
    public ApiResponse create() {
        return new ApiResponse(HttpStatus.CREATED, "Success");
    }
}

使用 curl 测试结果。现在 http 响应代码是 201。如果您更改 HttpStatus 中的 ApiResponse,http 状态响应代码将更改。

$ curl -v -X POST http://localhost:8080/test
*   Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 8080 (#0)
> POST /test HTTP/1.1
> ...
>
< HTTP/1.1 201
< Content-Type: application/json
< Transfer-Encoding: chunked
< Date: Mon, 05 Jul 2021 03:45:00 GMT
<
{"timestamp":0,"status":201,"error":null,"message":"Success","path":null}* Connection #0 to host localhost left intact
相关问题