1
0
mirror of https://gitee.com/coder-xiaomo/flashsale synced 2025-01-10 11:48:14 +08:00
Code Issues Projects Releases Wiki Activity GitHub Gitee

定义通用的返回对象--返回正确信息

This commit is contained in:
程序员小墨 2022-03-01 17:57:36 +08:00
parent 829cafa95d
commit 9a83cc0233
3 changed files with 49 additions and 4 deletions

View File

@ -19,7 +19,7 @@
预期效果:
```json
{"id":1,"name":"admin","gender":2,"age":18,"telephone":"110"}
{"data":{"id":1,"name":"admin","gender":2,"age":18,"telephone":"110"},"status":"success"}
```
### 层次结构以User为例自上向下
@ -40,4 +40,6 @@
| Mapping | resources/mapping | Mapper接口实现类 | xml格式SQL语句 | mapping/UserDOMapper.xml |
| Data Object | dataobject | 类 class | | dataobject.UserDO |
**Tips:** Model与Data Object并非完全一一对应例如UserModel是由ServiceImpl将UserDO和UserPasswordDO组装而成的。
**Tips:** Model与Data Object并非完全一一对应例如UserModel是由ServiceImpl将UserDO和UserPasswordDO组装而成的。
response: 用于处理HTTP请求返回

View File

@ -1,6 +1,7 @@
package com.cxyxiaomo.flashsale.controller;
import com.cxyxiaomo.flashsale.controller.viewobject.UserVO;
import com.cxyxiaomo.flashsale.response.CommonReturnType;
import com.cxyxiaomo.flashsale.service.UserService;
import com.cxyxiaomo.flashsale.service.model.UserModel;
import org.apache.catalina.User;
@ -20,11 +21,15 @@ public class UserController {
@RequestMapping("/get")
@ResponseBody
public UserVO getUser(@RequestParam(name = "id") Integer id) {
public CommonReturnType getUser(@RequestParam(name = "id") Integer id) {
// 调用Services服务获取对应id的用户对象并返回给前端
UserModel userModel = userService.getUserById(id);
// 将核心领域模型用户对象转化为可供UI使用的viewobject
return convertFromModel(userModel);
UserVO userVO = convertFromModel(userModel);
// 返回通用对象
CommonReturnType commonReturnType = CommonReturnType.create(userVO);
return commonReturnType;
}
private UserVO convertFromModel(UserModel userModel) {

View File

@ -0,0 +1,38 @@
package com.cxyxiaomo.flashsale.response;
public class CommonReturnType {
// 表明对应请求的返回处理结果 "success" "fail"
private String Status;
// status == "success" 则data内返回前端需要的JSON数据
// status == "fail" 则data内使用通用的错误码格式
private Object Data;
// 定义一个通用的创建方法
public static CommonReturnType create(Object result) {
return CommonReturnType.create(result, "success");
}
public static CommonReturnType create(Object result, String status) {
CommonReturnType type = new CommonReturnType();
type.setStatus(status);
type.setData(result);
return type;
}
public String getStatus() {
return Status;
}
public void setStatus(String status) {
Status = status;
}
public Object getData() {
return Data;
}
public void setData(Object data) {
Data = data;
}
}