SpringBoot 通用返回类设计
2024-08-28 11:30:46
在项目中通常需要为前端设计通过的返回类,返回的格式为:
{
"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);
}
最新文章
- Django根据现有数据库建立model
- Java线程面试题 Top 50 (转载)
- scala - Map基础
- 面向侧面的程序设计AOP-------《三》.Net平台AOP技术概览
- POJ 1208 The Blocks Problem
- Remember the Word,LA3942(Trie树+DP)
- JavaWeb中filter的详解及应用案例
- java获得平台相关的行分隔符和java路径分隔符的方法
- VSTO学习笔记(二)Excel对象模型
- 安装好.net framework后运行慢
- Struts国际化
- 怎么用VBS脚本自动注册yy娱乐的账号
- Winsock网络编程笔记(2)----基于TCP的server和client
- Java与算法之(2) - 快速排序
- 在 HTML5 中捕获音频和视频
- [Swift]LeetCode420. 强密码检验器 | Strong Password Checker
- 第五篇-ubuntu下插入U盘,显示可读系统。
- 面试 10:玩转 Java 选择和插入排序,附冒泡最终源码
- BSGS与exBSGS学习笔记
- LintCode翻转字符串问题 - python实现