springboot2.x basic tutorial: interface to achieve a unified format return

The interaction of front-end and back-end data is often involved in the SpringBoot project. At present, the data interaction based on json format is more popular. But json is just the format of the message, and the content in it needs to be designed by ourselves. Regardless of whether it is the HTTP interface or the RPC interface, it is important to maintain a uniform return value format, which will greatly reduce the cost of front-end and back-end joint debugging.

Defined interface specific format

{
	#返回状态码
	"code":integer类型,
	#返回信息描述
	"msg":string,
	#返回值
	"data":object
}

R type tools provided

@Data
public class R<T> {
    private int code;
    private T data;
    private String msg;
    public R() {
    }
    public static <T> R<T> ok(T data) {
        return fill(data,ApiCommonCodeEnum.OK);
    }
    public static <T> R<T> failed(String msg) {
        return fill( null, ApiCommonCodeEnum.FAIL);
    }
    public static <T> R<T> failed(ApiCommonCodeEnum apiEnum) {
        return fill( null, apiEnum);
    }
    public static <T> R<T> fill(T data, ApiCommonCodeEnum apiEnum) {
        return fill(apiEnum.getCode(),data,apiEnum.getMsg());
    }
    public static <T> R<T> fill(int code,T data,String msg) {
        R R = new R();
        R.setCode(code);
        R.setData(data);
        R.setMsg(msg);
        return R;
    }
}
//使用举例
@PostMapping("/login")
public R<UserInfoVO> login(@RequestBody LoginDTO loginDTO){
	UserInfoVO userInfoVO=new UserInfoVO();
	userInfoVO.setNickname("编程之家");
	userInfoVO.setToken("xxx");
	return R.ok(userInfoVO);
}

Status code design

Here we can refer to the Http status code design. Each business type defines a status code interval, which is extracted and placed in the enumeration class

public enum  ApiCommonCodeEnum {
    FAIL(1,"调用出错"),
    OK(0,"调用成功"),
	USER_EXISIT(100,"用户不存在"),
	USER_PASSWORD_ERROR(101,"用户密码错误"),
	//....
	NO_PERM(300,"无权限");
	//....
    int code;
    String msg;
    ApiCommonCodeEnum(int code,String msg){
        this.code=code;
        this.msg=msg;
    }
    public int getCode() {
        return code;
    }
    private void setCode(int code) {
        this.code = code;
    }
    public String getMsg() {
        return msg;
    }
    private void setMsg(String msg) {
        this.msg = msg;
    }
}

A thousand miles begins with a single step. Here is the second article in the SpringBoot tutorial series. All project source codes can be downloaded on my GitHub .

Guess you like

Origin blog.csdn.net/github_35592621/article/details/108248745