Spring Boot configuration unified format Result return value

Keywords: Spring Lombok Web Development Attribute

In web development, the separation of front and back development has been deeply rooted in the hearts of the people. Such a development mode is very useful for the development of elegant and beautiful web applications. I have consulted some materials on the Internet and learned to use the unified format return value in the Spring Boot development, which is conducive to the collaborative development of front-end small partners. Here is a summary:

Here, I use Lombok, an auxiliary framework, which can implement the Getter/Setter method requirements of Class, and the parameterless / parameterless constructor and Builder implementation through a few simple annotations, without actually writing them.

You can easily use the above functions by adding the following dependencies:

<!-- Lombok -->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.8</version>
</dependency>

The specific use method can refer to the relevant materials.

First, I wrote an enumeration ResultCode:

public enum ResultCode {
    SUCCESS(0,"Success"),
    SYSTEM_ERROR(500,"System error"),
    PARAM_IS_INVALID(1000,"Parameter error"),
    USER_IS_EXISTED(1001,"User already exists");
    private Integer status;
    private String message;
    ResultCode(Integer status,String message){
        this.status=status;
        this.message=message;
    }
    public Integer status(){
        return this.status;
    }
    public String message(){
        return this.message;
    }
}

This enumeration class is very simple. It has two properties, status and message. I have defined several enumeration instances internally, which represent several states of the server and their corresponding description messages. A fixed identity is provided for the upper Result encapsulation.

First, let's talk about the encapsulation of normal return value without exception:

First, I wrote a Result class, as follows:

@Data
public class Result<T> {

    private Integer status;
    private String desc;
    @Setter
    private T data;

    public static Result succ(){
        Result result=new Result();
        result.setResultCode(ResultCode.SUCCESS);
        return result;
    }

    public static Result succ(Object data){
        Result result=new Result();
        result.setResultCode(ResultCode.SUCCESS);
        result.setData(data);
        return result;
    }

    public static Result fail(Integer status,String desc){
        Result result=new Result();
        result.setStatus(status);
        result.setDesc(desc);
        return result;
    }

    public static Result fail(ResultCode resultCode){
        Result result=new Result();
        result.setResultCode(resultCode);
        return result;
    }

    private void setResultCode(ResultCode resultCode){
        this.status=resultCode.status();
        this.desc=resultCode.message();
    }
}

Result is a further encapsulation of ResultCode. It adds a generic attribute data, which is used to store the raw data without encapsulation. It contains two succ methods, which indicates the successful processing of the request and the return. succ() returns null, indicating that no data is returned but the processing is successful. succ(Object) encapsulates the return value into the result unified format and returns it to the front end.

After the Result encapsulation is completed, Spring AOP related classes need to be used for processing, and the ResponseBodyAdvice interface needs to be used here, which is an AOP interface of Spring for enhancing the response return value.

I implemented the interface:

@ControllerAdvice(basePackages = "com.welfarezhu.boot.demo")
public class ResponseHandler implements ResponseBodyAdvice {
    
    //The function takes effect when the return value is true
    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {

        if (o instanceof String){
            return JsonUtil.toJsonString(Result.succ(o));
        }
        return Result.succ(o);
    }
}

For the beforeBodyWrite method, here we only need to pay attention to the first parameter Object o, which is the value returned from the Controller processing. You can see the IF statement in it. Since java String type needs JSON tool transformation to produce the desired result, this IF statement is necessary.

Write a Controller to test:

Here we use a User entity class:

@Data
@Table
public class User {

    @Id
    @KeySql(useGeneratedKeys = true)
    private int id;
    private  String name;
    private String address;
    private int age;
    private String phoneNum;

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", address='" + address + '\'' +
                ", age=" + age +
                ", phoneNum='" + phoneNum + '\'' +
                '}';
    }
}

Write Controller:

@RestController
@Slf4j
public class HelloController {

    @GetMapping("/hello")
    public String hello(){
        int count=2080;
        return "Hello , "+count;
    }

    @GetMapping("/userInfo")
    public User outputUser(){
        User user=new User();
        user.setId(1001);
        user.setName("Bob");
        user.setAddress("The U.S.A");
        user.setAge(24);
        user.setPhoneNum("13200001111");
        return user;
    }
}

Start Spring Boot and access / hello. The result is as follows

{"status":0,"desc":"Success","data":"Hello , 2080"}

Visit / userInfo and the result is as follows:

{
  "status": 0,
  "desc": "Success",
  "data": {
    "id": 1001,
    "name": "Jian Fei Zhu",
    "address": "Lingbao City, Henan Province",
    "age": 24,
    "phoneNum": "13200001111"
  }
}

Such result encapsulation is very friendly to front-end developers.

Published 5 original articles, won praise 1, visited 30
Private letter follow

Posted by bobbybrown on Wed, 15 Jan 2020 19:52:49 -0800