SpringBoot+Response如何统一返回result结果集
作者:蚂蚁舞
这篇文章主要介绍了SpringBoot+Response如何统一返回result结果集,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
SpringBoot+Response统一返回result结果集
在SpringBoot开发接口中,通常会对java api统一返回result结果集,前端或者调用放可以根据返回的result结果集判断请求得到的数据是否正确,是否有效,一般情况下,使用java自定义的result结果集封装。
java统一返回数据格式
Response.java
//import com.fasterxml.jackson.annotation.JsonInclude; /** * 蚂蚁舞 */ //@JsonInclude(JsonInclude.Include.NON_NULL) public class Response { private boolean state; private int code; private String msg; private Object data; private long timestamp; public Response() {} public Response(boolean state, int code, String msg) { this.state = state; this.code = code; this.msg = msg; this.timestamp = System.currentTimeMillis()/1000; } public Response(boolean state, int code, String msg, Object data) { this.state = state; this.code = code; this.msg = msg; this.data = data; this.timestamp = System.currentTimeMillis()/1000; } public boolean isState() { return state; } public void setState(boolean state) { this.state = state; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } 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 long getTimestamp() { return timestamp; } public void setTimestamp(long timestamp) { this.timestamp = timestamp; } @Override public String toString() { return "Response{" + "state=" + state + ", code=" + code + ", msg='" + msg + '\'' + ", data=" + data + ", timestamp=" + timestamp + '}'; } }
java返回结果统一封装 静态类
ResponseCode.java
/** * 蚂蚁舞 */ public class ResponseCode { private static final boolean STATE_TRUE = true; private static final boolean STATE_FALSE = false; private static final int CODE_200 = 200; //操作资源成功 private static final int CODE_201 = 201; //资源为空 private static final int CODE_100 = 100; //操作资源失败 private static final int CORE_101 = 101; //缺少必要参数 private static final int CORE_102 = 102; //参数无效返回 private static final int CORE_303 = 303; //请求token无效或者token失效到期 提示前端后,前端用户可手动刷新重新登陆 private static final int CORE_304 = 304; //请求token无效或者token失效到期 提示前端后,前端自动跳转到登录页面 private static final int CORE_305 = 305; //未携带token认证信息,提示前端后,前端用户可手动刷新重新登陆 private static final int CORE_306 = 306; //未携带token认证信息,提示前端后,前端自动跳转到登录页面 private static final int CORE_307 = 307; //未登录 前端用户可手动跳转到登录页面 private static final int CORE_308 = 308; //未登录 前端自动跳转到登录页面 private static final int CORE_400 = 400; //全局异常 private static final int CORE_600 = 600; //您的权限不够 private static final int CORE_601 = 601; //未经授权不可访问 private static final String MSG_ALL_SUCCESS = "操作资源成功"; private static final String MSG_SELECT_SUCCESS = "获取资源成功"; private static final String MSG_UPDATE_SUCCESS = "更新资源成功"; private static final String MSG_INSERT_SUCCESS = "新增资源成功"; private static final String MSG_REMOVE_SUCCESS = "移除资源成功"; private static final String MSG_DELETE_SUCCESS = "删除资源成功"; private static final String MSG_ALL_FAIL = "操作资源失败"; private static final String MSG_SELECT_FAIL = "获取资源失败"; private static final String MSG_UPDATE_FAIL = "更新资源失败"; private static final String MSG_INSERT_FAIL = "新增资源失败"; private static final String MSG_REMOVE_FAIL = "移除资源失败"; private static final String MSG_DELETE_FAIL = "删除资源失败"; private static final String MSG_RESOURCES_EMPTY = "资源为空"; private static final String MSG_PARAMETER_LACK = "缺少必要参数"; private static final String MSG_PARAMETER_INVALID = "参数无效"; private static final String MSG_EXCEPTION_GLOBAL = "操作异常,请重新尝试"; private static final String MSG_TOKEN_INVALID = "请求token无效或者token失效到期"; private static final String MSG_TOKEN_INVALID_SKIP = "请求token无效或者token失效到期,自动跳转登录页"; private static final String MSG_TOKEN_NO_AUTH = "未携带token认证信息,请重新登陆"; private static final String MSG_TOKEN_NO_AUTH_SKIP = "未携带token认证信息,请重新登陆, 自动跳转到登录页"; private static final String MSG_TOKEN_NO_LOGIN = "未登录,请登录"; private static final String MSG_TOKEN_NO_LOGIN_SKIP = "未登录,请登录 自动跳转到登录页"; private static final String MSG_TOKEN_NO_PERMISSION = "未经授权的不可访问"; private static final String MSG_TOKEN_NOT_PERMISSION = "您的权限不足"; /** * 未登录,请登录 */ public static Response noLoginResponse(){ return new Response(STATE_FALSE,CORE_307,MSG_TOKEN_NO_LOGIN); } public static Response noLoginResponse(String msg){ return new Response(STATE_FALSE,CORE_307,msg); } public static Response noLoginSkipResponse(){ return new Response(STATE_FALSE,CORE_308,MSG_TOKEN_NO_LOGIN_SKIP); } public static Response noLoginSkipResponse(String msg){ return new Response(STATE_FALSE,CORE_308,msg); } // 未携带token认证信息,请重新登陆 public static Response noAuthHeaderTokenResponse(){ return new Response(STATE_FALSE,CORE_305,MSG_TOKEN_NO_AUTH); } public static Response noAuthHeaderTokenResponse(String msg){ return new Response(STATE_FALSE,CORE_305,msg); } // 未携带token认证信息,提示前端后,前端自动跳转到登录页面 public static Response noAuthHeaderTokenSkipResponse(){ return new Response(STATE_FALSE,CORE_306,MSG_TOKEN_NO_AUTH_SKIP); } public static Response noAuthHeaderTokenSkipResponse(String msg){ return new Response(STATE_FALSE,CORE_306,msg); } // 请求token无效或者token失效到期 public static Response invalidHeaderTokenResponse(){ return new Response(STATE_FALSE,CORE_303,MSG_TOKEN_INVALID); } public static Response invalidHeaderTokenResponse(String msg){ return new Response(STATE_FALSE,CORE_303,msg); } // 请求token无效或者token失效到期 前端可根据此项code跳转到登录页 public static Response invalidHeaderTokenSkipResponse(){ return new Response(STATE_FALSE,CORE_304,MSG_TOKEN_INVALID_SKIP); } public static Response invalidHeaderTokenSkipResponse(String msg){ return new Response(STATE_FALSE,CORE_304,msg); } // 全局异常返回 public static Response exceptionResponse(){ return new Response(STATE_FALSE,CORE_400,MSG_EXCEPTION_GLOBAL); } public static Response exceptionResponse(String msg){ return new Response(STATE_FALSE,CORE_400,msg); } // 您的权限不足 public static Response notPermissionResponse(){ return new Response(STATE_FALSE,CORE_600,MSG_TOKEN_NOT_PERMISSION); } public static Response notPermissionResponse(String msg){ return new Response(STATE_FALSE,CORE_600,msg); } // 未经授权的不可访问 public static Response unauthorizedPermissionResponse(){ return new Response(STATE_FALSE,CORE_601,MSG_TOKEN_NO_PERMISSION); } public static Response unauthorizedPermissionResponse(String msg){ return new Response(STATE_FALSE,CORE_601,msg); } // 缺少必要参数返回 public static Response lackParameterResponse(){ return new Response(STATE_FALSE, CORE_101, MSG_PARAMETER_LACK); } public static Response lackParameterResponse(String msg){ return new Response(STATE_FALSE, CORE_101, msg); } // 参数无效通用返回 public static Response invalidParameterResponse(){ return new Response(STATE_FALSE, CORE_102, MSG_PARAMETER_INVALID); } public static Response invalidParameterResponse(String msg){ return new Response(STATE_FALSE, CORE_102, msg); } // 新增成功返回 public static Response successInsertResponse(){ return new Response(STATE_TRUE,CODE_200,MSG_INSERT_SUCCESS); } public static Response successInsertResponse(Object data){ return new Response(STATE_TRUE,CODE_200,MSG_INSERT_SUCCESS,data); } // 更新成功返回 public static Response successUpdateResponse(){ return new Response(STATE_TRUE,CODE_200,MSG_UPDATE_SUCCESS); } // 查询成功返回 public static Response successSelectResponse(){ return new Response(STATE_TRUE,CODE_200,MSG_SELECT_SUCCESS); } public static Response successSelectResponse(Object data){ return new Response(STATE_TRUE, CODE_200, MSG_SELECT_SUCCESS, data); } // 移除成功返回 public static Response successRemoveResponse(){ return new Response(STATE_TRUE,CODE_200,MSG_REMOVE_SUCCESS); } // 删除成功返回 public static Response successDeleteResponse(){ return new Response(STATE_TRUE,CODE_200,MSG_DELETE_SUCCESS); } // 通用success返回 public static Response successResponse(){ return new Response(STATE_TRUE,CODE_200,MSG_ALL_SUCCESS); } public static Response successResponse(String msg){ return new Response(STATE_TRUE,CODE_200,msg); } public static Response successResponse(Object data){ return new Response(STATE_TRUE,CODE_200,MSG_ALL_SUCCESS, data); } public static Response successResponse(String msg, Object data){ return new Response(STATE_TRUE,CODE_200,msg, data); } // 查询结果为空时成功返回(没有获取到数据) public static Response successEmptyResponse(){ return new Response(STATE_TRUE,CODE_201,MSG_RESOURCES_EMPTY); } public static Response successEmptyResponse(String msg){ return new Response(STATE_TRUE,CODE_201,msg); } public static Response successEmptyResponse(Object data){ return new Response(STATE_TRUE,CODE_201,MSG_RESOURCES_EMPTY,data); } // 新增失败返回 public static Response failInsertResponse(){ return new Response(STATE_FALSE,CODE_100,MSG_INSERT_FAIL); } public static Response failInsertResponse(String msg){ return new Response(STATE_FALSE,CODE_100,msg); } // 更新失败返回 public static Response failUpdateResponse(){ return new Response(STATE_FALSE,CODE_100,MSG_UPDATE_FAIL); } public static Response failUpdateResponse(String msg){ return new Response(STATE_FALSE,CODE_100,msg); } // 查询失败返回 public static Response failSelectResponse(){ return new Response(STATE_FALSE,CODE_100,MSG_SELECT_FAIL); } public static Response failSelectResponse(String msg){ return new Response(STATE_FALSE,CODE_100,msg); } // 移除失败返回 public static Response failRemoveResponse(){ return new Response(STATE_FALSE,CODE_100,MSG_REMOVE_FAIL); } public static Response failRemoveResponse(String msg){ return new Response(STATE_FALSE,CODE_100,msg); } // 删除失败返回 public static Response failDeleteResponse(){ return new Response(STATE_FALSE,CODE_100,MSG_DELETE_FAIL); } public static Response failDeleteResponse(String msg){ return new Response(STATE_FALSE,CODE_100,msg); } // 通用fail返回 public static Response failResponse(){ return new Response(STATE_FALSE,CODE_100,MSG_ALL_FAIL); } public static Response failResponse(String msg){ return new Response(STATE_FALSE,CODE_100,msg); } public static Response failResponse(String msg, Object data){ return new Response(STATE_FALSE,CODE_100,msg,data); } // 自定义返回结果 public static Response customizeResponse(boolean state, int code, String msg){ return new Response(state,code,msg); } public static Response customizeResponse(boolean state, int code, String msg, Object data){ return new Response(state, code, msg, data); } }
springboot result统一的结果集处理
1 url的命名
在实际开发中名词居多,见名知意
- get 获取数据
- post 添加数据
- put 修改数据
- delete 逻辑假删除
2 返回数据的格式
2.1 一般返回的是json数据 {状态码: 信息}
**一些常用的返回状态码 **
2.2 直接在Controller中调用静态方法
- 2.2.1 先创建一个返回集的接口
public interface Result<T> { }
- 2.2.2 定义返回信息枚举类型
public enum StatusTypeEnum { /** * 200为成功 * 404为错误信息 */ SUCCESS(200,"success"), ERROR(404,"error"); private String msg; private int status; StatusTypeEnum(int status, String msg) { this.status = status; this.msg = msg; } }
- 2.2.3 创建successResult返回集继承返回集接口
@Data @AllArgsConstructor @NoArgsConstructor public class SuccessResult<T> implements Result<T> { private StatusTypeEnum status; private T data; public static SuccessResult succes() { return new SuccessResult<>(StatusTypeEnum.SUCCESS, null); } public static <T> SuccessResult succes(T data) { return new SuccessResult<>(StatusTypeEnum.SUCCESS, data); } }
- 2.2.4 创建errorResult返回集继承返回集接口
@Data @NoArgsConstructor @AllArgsConstructor public class ErrorResult implements Result { private StatusTypeEnum status; private String msg; public static ErrorResult error(int status, Exception ex) { return new ErrorResult(StatusTypeEnum.ERROR, ex.getMessage()); } public static ErrorResult error() { return new ErrorResult(StatusTypeEnum.ERROR, "错误"); } }
定义的内容需要根据业务不同来定,这个只是大体架构
2.3 利用AOP切面变成
@RestControllerAdvice + 实现ResponseBodyAdvice
将Result 封装到aop 中, Controller层 直接返回 参数,让aop去判断,返回的Result
@RestControllerAdvice @Slf4j public class GlobalResultAdvice implements ResponseBodyAdvice { @Override public boolean supports(MethodParameter returnType, Class converterType) { log.error("supports"); //为false 将不执行下面的aop方法 return true; } /** * * @param body * @param returnType * @param selectedContentType * @param selectedConverterType * @param request * @param response * @return */ @Override public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) { Object resp = null; if (body instanceof SuccessResult){ resp = body; }else{ resp = SuccessResult.succes(body); } return resp; } }
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。