也称为DTO(Data Transfer Object),将返回的结果统一通过一个包装类来返回,可以包括状态码code,描述信息msg,和返回的对象data。这里的data可以使用泛型来表示。

示例1

  1. import lombok.Data;
  2. /**
  3. * @author zhanghuiwen
  4. * http返回值
  5. */
  6. @Data
  7. public class Result<T> {
  8. public Result(boolean success, int code) {
  9. this.setSuccess(success);
  10. this.setCode(code);
  11. }
  12. public Result(boolean success, int code, T data) {
  13. this.setSuccess(success);
  14. this.setCode(code);
  15. this.setData(data);
  16. }
  17. public Result(boolean success, int code, String msg) {
  18. this.setSuccess(success);
  19. this.setCode(code);
  20. this.setData(data);
  21. }
  22. /**
  23. * 请求是否成功
  24. * true:成功
  25. * false:失败
  26. */
  27. private boolean success;
  28. /**
  29. * 状态码
  30. * 成功:200
  31. * 失败:其他
  32. */
  33. private int code;
  34. /**
  35. * 失败状态码描述
  36. * 如果成功不返回
  37. * 失败返回状态码对应的msg消息
  38. */
  39. private String msg;
  40. /**
  41. * 请求数据的结果
  42. */
  43. private T data;
  44. public static <T> Result<T> success() {
  45. return new Result<T>(true, 200);
  46. }
  47. public static <T> Result<T> success(T data) {
  48. return new Result<T>(true, 200, data);
  49. }
  50. public static <T> Result<T> fail(HttpStatusEnum httpStatusEnum) {
  51. return new Result<T>(false, httpStatusEnum.code(), httpStatusEnum.reasonPhraseUS());
  52. }
  53. public static <T> Result<T> fail(HttpStatusEnum httpStatusEnum, String msg) {
  54. return new Result<T>(false, httpStatusEnum.code(), msg);
  55. }
  56. }

这里还需要配合一个枚举类

  1. /**
  2. * http所有状态码枚举
  3. */
  4. public enum HttpStatusEnum {
  5. /**
  6. * http状态码枚举所有状态码注解
  7. */
  8. CONTINUE(100, "Continue", "请继续发送请求的剩余部分"),
  9. SWITCHING_PROTOCOLS(101, "Switching Protocols", "协议切换"),
  10. PROCESSING(102, "Processing", "请求将继续执行"),
  11. CHECKPOINT(103, "Checkpoint", "可以预加载"),
  12. OK(200, "OK", "请求已经成功处理"),
  13. CREATED(201, "Created", "请求已经成功处理,并创建了资源"),
  14. ACCEPTED(202, "Accepted", "请求已经接受,等待执行"),
  15. NON_AUTHORITATIVE_INFORMATION(203, "Non-Authoritative Information", "请求已经成功处理,但是信息不是原始的"),
  16. NO_CONTENT(204, "No Content", "请求已经成功处理,没有内容需要返回"),
  17. RESET_CONTENT(205, "Reset Content", "请求已经成功处理,请重置视图"),
  18. PARTIAL_CONTENT(206, "Partial Content", "部分Get请求已经成功处理"),
  19. MULTI_STATUS(207, "Multi-Status", "请求已经成功处理,将返回XML消息体"),
  20. ALREADY_REPORTED(208, "Already Reported", "请求已经成功处理,一个DAV的绑定成员被前一个请求枚举,并且没有被再一次包括"),
  21. IM_USED(226, "IM Used", "请求已经成功处理,将响应一个或者多个实例"),
  22. MULTIPLE_CHOICES(300, "Multiple Choices", "提供可供选择的回馈"),
  23. MOVED_PERMANENTLY(301, "Moved Permanently", "请求的资源已经永久转移"),
  24. FOUND(302, "Found", "请重新发送请求"),
  25. // MOVED_TEMPORARILY(302, "Moved Temporarily", "") 已经过时
  26. SEE_OTHER(303, "See Other", "请以Get方式请求另一个URI"),
  27. NOT_MODIFIED(304, "Not Modified", "资源未改变"),
  28. USE_PROXY(305, "Use Proxy", "请通过Location域中的代理进行访问"),
  29. // 306在新版本的规范中被弃用
  30. TEMPORARY_REDIRECT(307, "Temporary Redirect", "请求的资源临时从不同的URI响应请求"),
  31. RESUME_INCOMPLETE(308, "Resume Incomplete", "请求的资源已经永久转移"),
  32. BAD_REQUEST(400, "Bad Request", "请求错误,请修正请求"),
  33. UNAUTHORIZED(401, "Unauthorized", "没有被授权或者授权已经失效"),
  34. PAYMENT_REQUIRED(402, "Payment Required", "预留状态"),
  35. FORBIDDEN(403, "Forbidden", "请求被理解,但是拒绝执行"),
  36. NOT_FOUND(404, "Not Found", "资源未找到"),
  37. METHOD_NOT_ALLOWED(405, "Method Not Allowed", "请求方法不允许被执行"),
  38. NOT_ACCEPTABLE(406, "Not Acceptable", "请求的资源不满足请求者要求"),
  39. PROXY_AUTHENTICATION_REQUIRED(407, "Proxy Authentication Required", "请通过代理进行身份验证"),
  40. REQUEST_TIMEOUT(408, "Request Timeout", "请求超时"),
  41. CONFLICT(409, "Conflict", "请求冲突"),
  42. GONE(410, "Gone", "请求的资源不可用"),
  43. LENGTH_REQUIRED(411, "Length Required", "Content-Length未定义"),
  44. PRECONDITION_FAILED(412, "Precondition Failed", "不满足请求的先决条件"),
  45. REQUEST_ENTITY_TOO_LARGE(413, "Request Entity Too Large", "请求发送的实体太大"),
  46. REQUEST_URI_TOO_LONG(414, "Request-URI Too Long", "请求的URI超长"),
  47. UNSUPPORTED_MEDIA_TYPE(415, "Unsupported Media Type", "请求发送的实体类型不受支持"),
  48. REQUESTED_RANGE_NOT_SATISFIABLE(416, "Requested range not satisfiable", "Range指定的范围与当前资源可用范围不一致"),
  49. EXPECTATION_FAILED(417, "Expectation Failed", "请求头Expect中指定的预期内容无法被服务器满足"),
  50. // I_AM_A_TEAPOT(418, "I'm a teapot", ""), 该代码没有被服务器实现
  51. // INSUFFICIENT_SPACE_ON_RESOURCE(419, "Insufficient Space On Resource", ""), 已经过时
  52. // METHOD_FAILURE(420, "Method Failure", ""), 已经过时
  53. // DESTINATION_LOCKED(421, "Destination Locked", ""), 已经过时
  54. UNPROCESSABLE_ENTITY(422, "Unprocessable Entity", "请求格式正确,但是由于含有语义错误,无法响应"),
  55. LOCKED(423, "Locked", "当前资源被锁定"),
  56. FAILED_DEPENDENCY(424, "Failed Dependency", "由于之前的请求发生错误,导致当前请求失败"),
  57. UPGRADE_REQUIRED(426, "Upgrade Required", "客户端需要切换到TLS1.0"),
  58. PRECONDITION_REQUIRED(428, "Precondition Required", "请求需要提供前置条件"),
  59. TOO_MANY_REQUESTS(429, "Too Many Requests", "请求过多"),
  60. REQUEST_HEADER_FIELDS_TOO_LARGE(431, "Request Header Fields Too Large", "请求头超大,拒绝请求"),
  61. INTERNAL_SERVER_ERROR(500, "Internal Server Error", "服务器内部错误"),
  62. NOT_IMPLEMENTED(501, "Not Implemented", "服务器不支持当前请求的部分功能"),
  63. BAD_GATEWAY(502, "Bad Gateway", "响应无效"),
  64. SERVICE_UNAVAILABLE(503, "Service Unavailable", "服务器维护或者过载,拒绝服务"),
  65. GATEWAY_TIMEOUT(504, "Gateway Timeout", "上游服务器超时"),
  66. HTTP_VERSION_NOT_SUPPORTED(505, "HTTP Version not supported", "不支持的HTTP版本"),
  67. VARIANT_ALSO_NEGOTIATES(506, "Variant Also Negotiates", "服务器内部配置错误"),
  68. INSUFFICIENT_STORAGE(507, "Insufficient Storage", "服务器无法完成存储请求所需的内容"),
  69. LOOP_DETECTED(508, "Loop Detected", "服务器处理请求时发现死循环"),
  70. BANDWIDTH_LIMIT_EXCEEDED(509, "Bandwidth Limit Exceeded", "服务器达到带宽限制"),
  71. NOT_EXTENDED(510, "Not Extended", "获取资源所需的策略没有被满足"),
  72. NETWORK_AUTHENTICATION_REQUIRED(511, "Network Authentication Required", "需要进行网络授权");
  73. private final int code;
  74. private final String reasonPhraseUS;
  75. private final String reasonPhraseCN;
  76. private static final int
  77. INFORMATIONAL = 1,
  78. SUCCESSFUL = 2,
  79. REDIRECTION = 3,
  80. CLIENT_ERROR = 4,
  81. SERVER_ERROR = 5;
  82. HttpStatusEnum(int code, String reasonPhraseUS, String reasonPhraseCN) {
  83. this.code = code;
  84. this.reasonPhraseUS = reasonPhraseUS;
  85. this.reasonPhraseCN = reasonPhraseCN;
  86. }
  87. public int code() {
  88. return code;
  89. }
  90. public String reasonPhraseUS() {
  91. return reasonPhraseUS;
  92. }
  93. public String reasonPhraseCN() {
  94. return reasonPhraseCN;
  95. }
  96. public static HttpStatusEnum valueOf(int code) {
  97. for (HttpStatusEnum httpStatus : values()) {
  98. if (httpStatus.code() == code) {
  99. return httpStatus;
  100. }
  101. }
  102. throw new IllegalArgumentException("No matching constant for [" + code + "]");
  103. }
  104. public boolean is1xxInformational() {
  105. return type() == INFORMATIONAL;
  106. }
  107. public boolean is2xxSuccessful() {
  108. return type() == SUCCESSFUL;
  109. }
  110. public boolean is3xxRedirection() {
  111. return type() == REDIRECTION;
  112. }
  113. public boolean is4xxClientError() {
  114. return type() == CLIENT_ERROR;
  115. }
  116. public boolean is5xxServerError() {
  117. return type() == SERVER_ERROR;
  118. }
  119. private int type() {
  120. return (int) code / 100;
  121. }
  122. }

示例2

  1. package com.learn.utils;
  2. import com.fasterxml.jackson.annotation.JsonIgnore;
  3. import com.fasterxml.jackson.databind.ObjectMapper;
  4. /**
  5. *
  6. * @Title: JSONResult.java
  7. * @Package com.learn.utils
  8. * @Description: 自定义响应数据结构
  9. * 本类可提供给 H5/ios/安卓/公众号/小程序 使用
  10. * 前端接受此类数据(json object)后,可自行根据业务去实现相关功能
  11. *
  12. * 200:表示成功
  13. * 500:表示错误,错误信息在msg字段中
  14. * 501:bean验证错误,不管多少个错误都以map形式返回
  15. * 502:拦截器拦截到用户token出错
  16. * 555:异常抛出信息
  17. * 556: 用户qq校验异常
  18. * @version V1.0
  19. */
  20. public class JSONResult {
  21. // 定义jackson对象
  22. private static final ObjectMapper MAPPER = new ObjectMapper();
  23. // 响应业务状态
  24. private Integer status;
  25. // 响应消息
  26. private String msg;
  27. // 响应中的数据
  28. private Object data;
  29. @JsonIgnore
  30. private String ok; // 不使用
  31. public static JSONResult build(Integer status, String msg, Object data) {
  32. return new JSONResult(status, msg, data);
  33. }
  34. public static JSONResult build(Integer status, String msg, Object data, String ok) {
  35. return new JSONResult(status, msg, data, ok);
  36. }
  37. public static JSONResult ok(Object data) {
  38. return new JSONResult(data);
  39. }
  40. public static JSONResult ok() {
  41. return new JSONResult(null);
  42. }
  43. public static JSONResult errorMsg(String msg) {
  44. return new JSONResult(500, msg, null);
  45. }
  46. public static JSONResult errorMap(Object data) {
  47. return new JSONResult(501, "error", data);
  48. }
  49. public static JSONResult errorTokenMsg(String msg) {
  50. return new JSONResult(502, msg, null);
  51. }
  52. public static JSONResult errorException(String msg) {
  53. return new JSONResult(555, msg, null);
  54. }
  55. public static JSONResult errorUserQQ(String msg) {
  56. return new JSONResult(556, msg, null);
  57. }
  58. public JSONResult() {
  59. }
  60. public JSONResult(Integer status, String msg, Object data) {
  61. this.status = status;
  62. this.msg = msg;
  63. this.data = data;
  64. }
  65. public JSONResult(Integer status, String msg, Object data, String ok) {
  66. this.status = status;
  67. this.msg = msg;
  68. this.data = data;
  69. this.ok = ok;
  70. }
  71. public JSONResult(Object data) {
  72. this.status = 200;
  73. this.msg = "OK";
  74. this.data = data;
  75. }
  76. public Boolean isOK() {
  77. return this.status == 200;
  78. }
  79. public Integer getStatus() {
  80. return status;
  81. }
  82. public void setStatus(Integer status) {
  83. this.status = status;
  84. }
  85. public String getMsg() {
  86. return msg;
  87. }
  88. public void setMsg(String msg) {
  89. this.msg = msg;
  90. }
  91. public Object getData() {
  92. return data;
  93. }
  94. public void setData(Object data) {
  95. this.data = data;
  96. }
  97. public String getOk() {
  98. return ok;
  99. }
  100. public void setOk(String ok) {
  101. this.ok = ok;
  102. }
  103. }

示例3

  1. package com.learn.videoservice.dto;
  2. import lombok.Data;
  3. /**
  4. * 用于封装返回类型
  5. * @author wujinhao
  6. * @param <T>
  7. */
  8. @Data
  9. public class ResponseObject<T> {
  10. private String code;
  11. private String msg;
  12. private T object;
  13. public ResponseObject(T... data) {
  14. this.code = "200";
  15. this.msg = "成功";
  16. if (data.length>0){
  17. this.object = data[0];
  18. }
  19. }
  20. /**
  21. * 仅返回code和msg
  22. * @param code
  23. * @param msg
  24. */
  25. public ResponseObject(String code, String msg){
  26. this.code=code;
  27. this.msg = msg;
  28. }
  29. /**
  30. * 返回全部
  31. * @param code
  32. * @param msg
  33. * @param object
  34. */
  35. public ResponseObject(String code, String msg, T object) {
  36. this.code = code;
  37. this.msg = msg;
  38. this.object = object;
  39. }
  40. }