自定义返回结果集
秋水 Lv4

首先明白为什么要自定义返回结果集

  1. 前后端进行交互的时候,便于交流
  2. 后端与后端之间的交互
  3. 使用不同的技术栈之间的交互

方法实现如下

  1. 定义一个状态接口StaruCode

    ​ 代码如下

    1
    2
    3
    4
    5
    6
    7
    package com.qiushui.Result;

    public interface StatusCode {
    public int getCode();
    public String getMsg();
    }

  2. 实现接口,并且定义返回状态码和消息

    代码如下

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    package com.qiushui.Result;

    import jdk.nashorn.internal.objects.annotations.Getter;


    public enum ResultCode implements StatusCode{

    SUCCESS(1000, "请求成功"),

    FAILED(1001, "请求失败"),
    VALIDATE_ERROR(1002, "参数校验失败"),
    RESPONSE_PACK_ERROR(1003, "response返回包装失败");

    private int code;
    private String msg;

    ResultCode(int code, String msg){
    this.code=code;
    this.msg = msg;
    }


    @Override
    public int getCode() {
    return this.code;
    }

    @Override
    public String getMsg() {
    return this.msg;
    }
    }

  3. 封装结果集

    代码如下

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    package com.qiushui.Result;

    public class ResultVo {
    //状态码
    private int code;
    //状态信息
    private String msg;
    //返回对象
    private Object data;


    //默认返回成功
    public ResultVo(Object data){
    this.code=ResultCode.SUCCESS.getCode();
    this.msg = ResultCode.SUCCESS.getMsg();
    this.data = data;
    }

    //返回指定状态码
    public ResultVo(StatusCode statusCode, Object data){
    this.code=statusCode.getCode();
    this.msg = statusCode.getMsg();
    }

    //只返回状态码
    // 只返回状态码
    public ResultVo(StatusCode statusCode) {
    this.code = statusCode.getCode();
    this.msg = statusCode.getMsg();
    this.data = null;
    }
    }

  • Post title:自定义返回结果集
  • Post author:秋水
  • Create time:2024-04-15 22:02:57
  • Post link:tai769.github.io2024/04/15/自定义返回结果集/
  • Copyright Notice:All articles in this blog are licensed under BY-NC-SA unless stating additionally.