参考:Spring Boot的通用返回类Result
Spring Boot的通用返回类Result_StillTogether的博客-CSDN博客
在上一篇文章中,我们会发现Controller中函数的返回值类型是一个Result
一般来说,后台返回给前端的数据格式都是固定的,比如如下
{
"code": 5000,
"data": [
{
"id": 8,
"name": "zyl",
"number": "2020112617",
"createdAt": "2021-10-19T12:32:08.497Z",
"updatedAt": "2021-10-20T02:57:34.580329Z",
"deletedAt": null
},
{
"id": 9,
"name": "喻鑫瑞",
"number": "123456789",
"createdAt": "2021-10-19T14:02:32.875243Z",
"updatedAt": "2021-10-19T14:02:32.875243Z",
"deletedAt": null
},
{
"id": 10,
"name": "喻鑫瑞2",
"number": "123456789",
"createdAt": "2021-10-19T14:06:18.663413Z",
"updatedAt": "2021-10-19T14:06:18.663413Z",
"deletedAt": null
},
{
"id": 11,
"name": "fahfahi",
"number": "215367164716",
"createdAt": "2021-10-20T02:31:34.55309Z",
"updatedAt": "2021-10-20T02:31:34.55309Z",
"deletedAt": null
},
{
"id": 12,
"name": "fafa",
"number": "215367164716",
"createdAt": "2021-10-20T02:31:42.429517Z",
"updatedAt": "2021-10-20T02:31:42.429517Z",
"deletedAt": null
}
],
"msg": "success",
"status": "ok"
}
{
"code": 5000,
"data": {
"id": 8,
"name": "zyl",
"number": "2020112617",
"createdAt": "2021-10-19T12:32:08.497Z",
"updatedAt": "2021-10-20T02:57:34.580329Z",
"deletedAt": null
},
"msg": "success",
"status": "ok"
}
那么,如何在Java中实现这样的功能呢?
只需要定义一个泛型的Result类即可
比如我们需要如下的返回结果
{
"code": 5000,
"msg": "success",
"status": "ok",
"data": [
{
"name": "zyl3",
"number": "123456"
},
{
"name": "zyl4",
"number": "123456"
},
{
"name": "yxr",
"number": "2020112617"
}
]
}
那么对应的字段即是:
字段 | 类型 | 作用 |
---|---|---|
code | Integer | 业务状态码 |
msg | String | 返回的提示信息 |
status | String | 返回的状态信息 |
data | T | 数据 |
对应的代码实现:
package com.example.demo2.springbootmybatis.utils;
public class Result<T> {
private Integer code;
private String msg;
private String status;
private T data;
public Result(Integer code, String msg, String status, T data) {
this.code = code;
this.msg = msg;
this.status = status;
this.data = data;
}
public Result(Integer code, String msg, String status) {
this.code = code;
this.msg = msg;
this.status = status;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
@Override
public String toString() {
return "Result{" +
"code=" + code +
", msg='" + msg + '\'' +
", status='" + status + '\'' +
", data=" + data +
'}';
}
}
那么我们在Controller中的函数返回值类型就可以使用我们的Result类
比如这样:
/**
* 查询所有
* */
@GetMapping("/all")
public Result<List<Test>> getAll(){
List<Test> list = testService.getAll();
return new Result<>(5000,"success","ok",list); //返回一个Result对象,Java会自动转换成JSON对象
}
如下图所示: