Spring Boot: Unified Response Body

Introduction

Front and rear separation is very popular nowadays, so how to design a good RESTful API and how to enable front end programmers to handle standard response JSON data structure are significant. In order for the front end to have a better logical display and page interaction processing, every RESTful request should contain the following information:
| Name | Description |
| —— | —— |
| status | Indicate the request success or not |
| errorCode | Give a specific error code to match the service exception |
| errorMsg | More specific error message |
| resultBody | Result, usually Bean object in JSON format |
Note: As for the resultBody, usually we declare it as Generic Class to adapt different return type.

Implementation

Define the generic return class

According to the form above, the Java Bean code would be like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Data
public final class CommonResult<T> {

private int status = 1;

private String errorCode = "";

private String errorMsg = "";

private T resultBody;

public CommonResult() {
}

public CommonResult(T resultBody) {
this.resultBody = resultBody;
}
}

Configuration

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@EnableWebMvc
@Configuration
public class UnifiedReturnConfig {

@RestControllerAdvice("com.example.unifiedreturn.api")
static class CommonResultResponseAdvice implements ResponseBodyAdvice<Object>{
@Override
public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
return true;
}

@Override
public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
if (body instanceof CommonResult){
return body;
}

return new CommonResult<Object>(body);
}
}
}

In this step, we create a static class CommonResultResponseAdvice which implementes interface ResponseBodyAdvice<Object>. By doing this, the response body will be intercepted and we override the method beforeBodyWrite() which can do conversion between body and our customized CommonResult.