在项目中通常需要为前端设计通过的返回类,返回的格式为:

{
"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);
}

最新文章

  1. Django根据现有数据库建立model
  2. Java线程面试题 Top 50 (转载)
  3. scala - Map基础
  4. 面向侧面的程序设计AOP-------《三》.Net平台AOP技术概览
  5. POJ 1208 The Blocks Problem
  6. Remember the Word,LA3942(Trie树+DP)
  7. JavaWeb中filter的详解及应用案例
  8. java获得平台相关的行分隔符和java路径分隔符的方法
  9. VSTO学习笔记(二)Excel对象模型
  10. 安装好.net framework后运行慢
  11. Struts国际化
  12. 怎么用VBS脚本自动注册yy娱乐的账号
  13. Winsock网络编程笔记(2)----基于TCP的server和client
  14. Java与算法之(2) - 快速排序
  15. 在 HTML5 中捕获音频和视频
  16. [Swift]LeetCode420. 强密码检验器 | Strong Password Checker
  17. 第五篇-ubuntu下插入U盘,显示可读系统。
  18. 面试 10:玩转 Java 选择和插入排序,附冒泡最终源码
  19. BSGS与exBSGS学习笔记
  20. LintCode翻转字符串问题 - python实现

热门文章

  1. py-faster-rcnn 训练自己的数据
  2. 把本地的jar包安装到maven库中
  3. Eclipse中JSP页面默认编码修改
  4. less.js
  5. [Algorithms] Topological Sort
  6. Ubuntu 16.04 安装google浏览器
  7. 【Trello】使用指南
  8. 【CSS选择器】理解汇总和记录
  9. HDU 1796 How many integers can you find(容斥原理)
  10. 疯狂Html+CSS+JS 中JS总结