也称为DTO(Data Transfer Object),将返回的结果统一通过一个包装类来返回,可以包括状态码code,描述信息msg,和返回的对象data。这里的data可以使用泛型来表示。
示例1
import lombok.Data;
/**
* @author zhanghuiwen
* http返回值
*/
@Data
public class Result<T> {
public Result(boolean success, int code) {
this.setSuccess(success);
this.setCode(code);
}
public Result(boolean success, int code, T data) {
this.setSuccess(success);
this.setCode(code);
this.setData(data);
}
public Result(boolean success, int code, String msg) {
this.setSuccess(success);
this.setCode(code);
this.setData(data);
}
/**
* 请求是否成功
* true:成功
* false:失败
*/
private boolean success;
/**
* 状态码
* 成功:200
* 失败:其他
*/
private int code;
/**
* 失败状态码描述
* 如果成功不返回
* 失败返回状态码对应的msg消息
*/
private String msg;
/**
* 请求数据的结果
*/
private T data;
public static <T> Result<T> success() {
return new Result<T>(true, 200);
}
public static <T> Result<T> success(T data) {
return new Result<T>(true, 200, data);
}
public static <T> Result<T> fail(HttpStatusEnum httpStatusEnum) {
return new Result<T>(false, httpStatusEnum.code(), httpStatusEnum.reasonPhraseUS());
}
public static <T> Result<T> fail(HttpStatusEnum httpStatusEnum, String msg) {
return new Result<T>(false, httpStatusEnum.code(), msg);
}
}
这里还需要配合一个枚举类
/**
* http所有状态码枚举
*/
public enum HttpStatusEnum {
/**
* http状态码枚举所有状态码注解
*/
CONTINUE(100, "Continue", "请继续发送请求的剩余部分"),
SWITCHING_PROTOCOLS(101, "Switching Protocols", "协议切换"),
PROCESSING(102, "Processing", "请求将继续执行"),
CHECKPOINT(103, "Checkpoint", "可以预加载"),
OK(200, "OK", "请求已经成功处理"),
CREATED(201, "Created", "请求已经成功处理,并创建了资源"),
ACCEPTED(202, "Accepted", "请求已经接受,等待执行"),
NON_AUTHORITATIVE_INFORMATION(203, "Non-Authoritative Information", "请求已经成功处理,但是信息不是原始的"),
NO_CONTENT(204, "No Content", "请求已经成功处理,没有内容需要返回"),
RESET_CONTENT(205, "Reset Content", "请求已经成功处理,请重置视图"),
PARTIAL_CONTENT(206, "Partial Content", "部分Get请求已经成功处理"),
MULTI_STATUS(207, "Multi-Status", "请求已经成功处理,将返回XML消息体"),
ALREADY_REPORTED(208, "Already Reported", "请求已经成功处理,一个DAV的绑定成员被前一个请求枚举,并且没有被再一次包括"),
IM_USED(226, "IM Used", "请求已经成功处理,将响应一个或者多个实例"),
MULTIPLE_CHOICES(300, "Multiple Choices", "提供可供选择的回馈"),
MOVED_PERMANENTLY(301, "Moved Permanently", "请求的资源已经永久转移"),
FOUND(302, "Found", "请重新发送请求"),
// MOVED_TEMPORARILY(302, "Moved Temporarily", "") 已经过时
SEE_OTHER(303, "See Other", "请以Get方式请求另一个URI"),
NOT_MODIFIED(304, "Not Modified", "资源未改变"),
USE_PROXY(305, "Use Proxy", "请通过Location域中的代理进行访问"),
// 306在新版本的规范中被弃用
TEMPORARY_REDIRECT(307, "Temporary Redirect", "请求的资源临时从不同的URI响应请求"),
RESUME_INCOMPLETE(308, "Resume Incomplete", "请求的资源已经永久转移"),
BAD_REQUEST(400, "Bad Request", "请求错误,请修正请求"),
UNAUTHORIZED(401, "Unauthorized", "没有被授权或者授权已经失效"),
PAYMENT_REQUIRED(402, "Payment Required", "预留状态"),
FORBIDDEN(403, "Forbidden", "请求被理解,但是拒绝执行"),
NOT_FOUND(404, "Not Found", "资源未找到"),
METHOD_NOT_ALLOWED(405, "Method Not Allowed", "请求方法不允许被执行"),
NOT_ACCEPTABLE(406, "Not Acceptable", "请求的资源不满足请求者要求"),
PROXY_AUTHENTICATION_REQUIRED(407, "Proxy Authentication Required", "请通过代理进行身份验证"),
REQUEST_TIMEOUT(408, "Request Timeout", "请求超时"),
CONFLICT(409, "Conflict", "请求冲突"),
GONE(410, "Gone", "请求的资源不可用"),
LENGTH_REQUIRED(411, "Length Required", "Content-Length未定义"),
PRECONDITION_FAILED(412, "Precondition Failed", "不满足请求的先决条件"),
REQUEST_ENTITY_TOO_LARGE(413, "Request Entity Too Large", "请求发送的实体太大"),
REQUEST_URI_TOO_LONG(414, "Request-URI Too Long", "请求的URI超长"),
UNSUPPORTED_MEDIA_TYPE(415, "Unsupported Media Type", "请求发送的实体类型不受支持"),
REQUESTED_RANGE_NOT_SATISFIABLE(416, "Requested range not satisfiable", "Range指定的范围与当前资源可用范围不一致"),
EXPECTATION_FAILED(417, "Expectation Failed", "请求头Expect中指定的预期内容无法被服务器满足"),
// I_AM_A_TEAPOT(418, "I'm a teapot", ""), 该代码没有被服务器实现
// INSUFFICIENT_SPACE_ON_RESOURCE(419, "Insufficient Space On Resource", ""), 已经过时
// METHOD_FAILURE(420, "Method Failure", ""), 已经过时
// DESTINATION_LOCKED(421, "Destination Locked", ""), 已经过时
UNPROCESSABLE_ENTITY(422, "Unprocessable Entity", "请求格式正确,但是由于含有语义错误,无法响应"),
LOCKED(423, "Locked", "当前资源被锁定"),
FAILED_DEPENDENCY(424, "Failed Dependency", "由于之前的请求发生错误,导致当前请求失败"),
UPGRADE_REQUIRED(426, "Upgrade Required", "客户端需要切换到TLS1.0"),
PRECONDITION_REQUIRED(428, "Precondition Required", "请求需要提供前置条件"),
TOO_MANY_REQUESTS(429, "Too Many Requests", "请求过多"),
REQUEST_HEADER_FIELDS_TOO_LARGE(431, "Request Header Fields Too Large", "请求头超大,拒绝请求"),
INTERNAL_SERVER_ERROR(500, "Internal Server Error", "服务器内部错误"),
NOT_IMPLEMENTED(501, "Not Implemented", "服务器不支持当前请求的部分功能"),
BAD_GATEWAY(502, "Bad Gateway", "响应无效"),
SERVICE_UNAVAILABLE(503, "Service Unavailable", "服务器维护或者过载,拒绝服务"),
GATEWAY_TIMEOUT(504, "Gateway Timeout", "上游服务器超时"),
HTTP_VERSION_NOT_SUPPORTED(505, "HTTP Version not supported", "不支持的HTTP版本"),
VARIANT_ALSO_NEGOTIATES(506, "Variant Also Negotiates", "服务器内部配置错误"),
INSUFFICIENT_STORAGE(507, "Insufficient Storage", "服务器无法完成存储请求所需的内容"),
LOOP_DETECTED(508, "Loop Detected", "服务器处理请求时发现死循环"),
BANDWIDTH_LIMIT_EXCEEDED(509, "Bandwidth Limit Exceeded", "服务器达到带宽限制"),
NOT_EXTENDED(510, "Not Extended", "获取资源所需的策略没有被满足"),
NETWORK_AUTHENTICATION_REQUIRED(511, "Network Authentication Required", "需要进行网络授权");
private final int code;
private final String reasonPhraseUS;
private final String reasonPhraseCN;
private static final int
INFORMATIONAL = 1,
SUCCESSFUL = 2,
REDIRECTION = 3,
CLIENT_ERROR = 4,
SERVER_ERROR = 5;
HttpStatusEnum(int code, String reasonPhraseUS, String reasonPhraseCN) {
this.code = code;
this.reasonPhraseUS = reasonPhraseUS;
this.reasonPhraseCN = reasonPhraseCN;
}
public int code() {
return code;
}
public String reasonPhraseUS() {
return reasonPhraseUS;
}
public String reasonPhraseCN() {
return reasonPhraseCN;
}
public static HttpStatusEnum valueOf(int code) {
for (HttpStatusEnum httpStatus : values()) {
if (httpStatus.code() == code) {
return httpStatus;
}
}
throw new IllegalArgumentException("No matching constant for [" + code + "]");
}
public boolean is1xxInformational() {
return type() == INFORMATIONAL;
}
public boolean is2xxSuccessful() {
return type() == SUCCESSFUL;
}
public boolean is3xxRedirection() {
return type() == REDIRECTION;
}
public boolean is4xxClientError() {
return type() == CLIENT_ERROR;
}
public boolean is5xxServerError() {
return type() == SERVER_ERROR;
}
private int type() {
return (int) code / 100;
}
}
示例2
package com.learn.utils;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
*
* @Title: JSONResult.java
* @Package com.learn.utils
* @Description: 自定义响应数据结构
* 本类可提供给 H5/ios/安卓/公众号/小程序 使用
* 前端接受此类数据(json object)后,可自行根据业务去实现相关功能
*
* 200:表示成功
* 500:表示错误,错误信息在msg字段中
* 501:bean验证错误,不管多少个错误都以map形式返回
* 502:拦截器拦截到用户token出错
* 555:异常抛出信息
* 556: 用户qq校验异常
* @version V1.0
*/
public class JSONResult {
// 定义jackson对象
private static final ObjectMapper MAPPER = new ObjectMapper();
// 响应业务状态
private Integer status;
// 响应消息
private String msg;
// 响应中的数据
private Object data;
@JsonIgnore
private String ok; // 不使用
public static JSONResult build(Integer status, String msg, Object data) {
return new JSONResult(status, msg, data);
}
public static JSONResult build(Integer status, String msg, Object data, String ok) {
return new JSONResult(status, msg, data, ok);
}
public static JSONResult ok(Object data) {
return new JSONResult(data);
}
public static JSONResult ok() {
return new JSONResult(null);
}
public static JSONResult errorMsg(String msg) {
return new JSONResult(500, msg, null);
}
public static JSONResult errorMap(Object data) {
return new JSONResult(501, "error", data);
}
public static JSONResult errorTokenMsg(String msg) {
return new JSONResult(502, msg, null);
}
public static JSONResult errorException(String msg) {
return new JSONResult(555, msg, null);
}
public static JSONResult errorUserQQ(String msg) {
return new JSONResult(556, msg, null);
}
public JSONResult() {
}
public JSONResult(Integer status, String msg, Object data) {
this.status = status;
this.msg = msg;
this.data = data;
}
public JSONResult(Integer status, String msg, Object data, String ok) {
this.status = status;
this.msg = msg;
this.data = data;
this.ok = ok;
}
public JSONResult(Object data) {
this.status = 200;
this.msg = "OK";
this.data = data;
}
public Boolean isOK() {
return this.status == 200;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public String getOk() {
return ok;
}
public void setOk(String ok) {
this.ok = ok;
}
}
示例3
package com.learn.videoservice.dto;
import lombok.Data;
/**
* 用于封装返回类型
* @author wujinhao
* @param <T>
*/
@Data
public class ResponseObject<T> {
private String code;
private String msg;
private T object;
public ResponseObject(T... data) {
this.code = "200";
this.msg = "成功";
if (data.length>0){
this.object = data[0];
}
}
/**
* 仅返回code和msg
* @param code
* @param msg
*/
public ResponseObject(String code, String msg){
this.code=code;
this.msg = msg;
}
/**
* 返回全部
* @param code
* @param msg
* @param object
*/
public ResponseObject(String code, String msg, T object) {
this.code = code;
this.msg = msg;
this.object = object;
}
}