在項目中通常需要為前端設計通過的返回類,返回的格式為:
{
"status": "success",
"data": {...}
}
定義通過返回類:CommonReturnType
/**
* 通用返回結果類
* 包含請求結果 status : "success" or "failed"
* 包含請求數據 data : {}
*/
public class CommonReturnType {
// 表明對應請求的返回處理結果為: "success" or "failed"
private String status;
// 若status=success, 則data內返回前端需要的json數據
// 若status=failed, 則data內使用通用的錯誤碼格式
private Object data;
// 通用靜態工廠方法
public static CommonReturnType create(Object result){
return CommonReturnType.create(result, "success");
}
// 封裝返回數據data
public static CommonReturnType create(Object result, String status){
CommonReturnType returnType = new CommonReturnType();
returnType.setStatus(status);
returnType.setData(result);
return returnType;
}
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;
}
}
在Controller中使用
@GetMapping("/get")
@ResponseBody
public CommonReturnType getUser(@RequestParam(name = "id") Integer id) throws BusinessException {
// 調用service服務獲取對應id的用戶對象並返回給前端
UserModel userModel = userService.getUserById(id);
// 獲取對應的用戶不存在
if(userModel == null){
throw new BusinessException(EnumBusinessError.USER_NOT_EXIST);
}
// 將核心領域模型用戶對象轉換為可供UI使用的ViewObject,而不是直接將UserModel返回給前端
UserVO userVO = convertFromModel(userModel);
// 返回通用對象
return CommonReturnType.create(userVO);
}