springboot后台返回值通用结构体CommonReturnType

springboot后台返回值通用结构体CommonReturnType

  • 背景
  • 代码

背景

在普通的web开发中,通常在请求数据后,controller会返回一个结构体给前端,比如:

public UserVO getUser(@RequestParam(name="id") Integer id)
{
     
     UserModel userModel = userService.getUserById(id);
     UserVO userVO = convertFromUserModel(userModel);
     return userVO;
     //return CommonReturnType.create(userVO);
 }

当userVO在获取失败的情况下,前端就只能收到一串tomcat容器返回的错误信息,可能会对前端的解析造成困扰,且对异常信息无法做出处理。

在此背景下,增加一层通用返回结构体,可以定义为CommonReturnType,具有两个属性如下:

public class CommonReturnType {
     
    private String status; //记录返回状态,success或者fail
    private Object data;	//返回有效内容。success时返回userVO,fail时返回自定义错误信息。
}

将其返回,就可以解决上面提到的问题。

代码

CommonReturnType定义:

public class CommonReturnType {
     
    private String status;
    private Object data;

    public static CommonReturnType create(Object result){
     
        return CommonReturnType.create(result,"sueccess");
    }

    public static CommonReturnType create(Object result, String status){
     
        CommonReturnType commonReturnType = new CommonReturnType();
        commonReturnType.setStatus(status);
        commonReturnType.setData(result);
        return commonReturnType;
    }
    public String getStatus() {
     
        return status;
    }

    public void setStatus(String status) {
     
        this.status = status;
    }

    public Object getData() {
     
        return data;
    }

    public void setData(Object data) {
     
        this.data = data;
    }
}

CommonReturnType的使用:

public CommonReturnType getUser(@RequestParam(name="id") Integer id)
    {
     
        UserModel userModel = userService.getUserById(id);
        UserVO userVO = convertFromUserModel(userModel);
        return CommonReturnType.create(userVO);
    }

你可能感兴趣的:(springboot)