(三)SpringBoot定义统一返回result对象

一:定义响应码枚举

package com.example.demo.core.ret;

/**
 * @Description: 响应码枚举,参考HTTP状态码的语义
 * @author 
 * @date 2018/4/19 09:42
 */
public enum RetCode {

   // 成功
   SUCCESS(200),

   // 失败
   FAIL(400),

   // 未认证(签名错误)
   UNAUTHORIZED(401),

   // 接口不存在
   NOT_FOUND(404),

   // 服务器内部错误
   INTERNAL_SERVER_ERROR(500);

   public int code;

   RetCode(int code) {
      this.code = code;
   }
}

  

二:创建返回对象实体(泛型)

package com.example.demo.core.ret;

import java.io.Serializable;

import com.alibaba.fastjson.JSON;

/**
 * @Description: 返回对象实体
 * @author 
 * @date 2018/4/19 09:43
 */
public class RetResult<T> {

   public int code;

   private String msg;

   private T data;

   public RetResult<T> setCode(RetCode retCode) {
      this.code = retCode.code;
      return this;
   }

   public int getCode() {
      return code;
   }

   public RetResult<T> setCode(int code) {
      this.code = code;
      return this;
   }

   public String getMsg() {
      return msg;
   }

   public RetResult<T> setMsg(String msg) {
      this.msg = msg;
      return this;
   }

   public T getData() {
      return data;
   }

   public RetResult<T> setData(T data) {
      this.data = data;
      return this;
   }

}

  说明:code为状态码、msg为提示信息、data为返回的数据

 

四:返回结果数据格式封装

package com.example.demo.core.ret;

/**
 * @Description: 将结果转换为封装后的对象
 * @author 
 * @date 2018/4/19 09:45
 */
public class RetResponse {

   private final static String SUCCESS = "success";

   public static <T> RetResult<T> makeOKRsp() {
      return new RetResult<T>().setCode(RetCode.SUCCESS).setMsg(SUCCESS);
   }

   public static <T> RetResult<T> makeOKRsp(T data) {
      return new RetResult<T>().setCode(RetCode.SUCCESS).setMsg(SUCCESS).setData(data);
   }

   public static <T> RetResult<T> makeErrRsp(String message) {
      return new RetResult<T>().setCode(RetCode.FAIL).setMsg(SUCCESS);
   }

   public static <T> RetResult<T> makeRsp(int code, String msg) {
      return new RetResult<T>().setCode(code).setMsg(msg);
   }
   
   public static <T> RetResult<T> makeRsp(int code, String msg, T data) {
      return new RetResult<T>().setCode(code).setMsg(msg).setData(data);
   }
}

  

五:功能测试

@RequestMapping("/selectById")
public RetResult<UserInfo> selectById(Integer id){
    UserInfo userInfo = userInfoService.selectById(id);
    return RetResponse.makeOKRsp(userInfo);
}

  改造后请求返回数据格式

{
    "code": 200,
    "msg": "success",
    "data": {
        "id": 1,
        "userName": "1"
    }
}

  

posted @ 2018-09-09 23:04  魔鬼YU天使  阅读(24503)  评论(2编辑  收藏  举报