统一返回状态码
1 package com.wb.response; 2 3 /** 4 * 统一返回状态码 5 */ 6 public enum ResultCode { 7 /* 成功状态码 */ 8 SUCCESS(1, "成功"), 9 /* 失败状态码 */ 10 FAILURE(0, "失败"); 11 12 13 private Integer code; 14 private String message; 15 16 ResultCode(Integer code, String message) { 17 this.code = code; 18 this.message = message; 19 } 20 21 public Integer code() { 22 return this.code; 23 } 24 25 public String message() { 26 return this.message; 27 } 28 29 public static Integer getCode(String name) { 30 return getItem(name).code; 31 } 32 33 34 public static String getMessage(String name) { 35 return getItem(name).message; 36 } 37 38 public static ResultCode getItem(String name) { 39 for (ResultCode item : ResultCode.values()) { 40 if (item.name().equals(name)) { 41 return item; 42 } 43 } 44 return null; 45 } 46 47 @Override 48 public String toString() { 49 return this.name(); 50 } 51 }
封装返回结果
1 package com.wb.response; 2 3 import lombok.Data; 4 5 import java.io.Serializable; 6 7 /** 8 * 响应结果统一封装 9 */ 10 @Data 11 public class Result implements Serializable { 12 13 private static final long serialVersionUID = -3948389268046368059L; 14 private Integer code; 15 private String msg; 16 private Object data; 17 18 19 public void setResultCode(ResultCode resultCode) { 20 this.code = resultCode.code(); 21 this.msg = resultCode.message(); 22 } 23 24 /** 25 * 请求成功不带返回值 26 */ 27 public static Result success() { 28 Result result = new Result(); 29 result.setResultCode(ResultCode.SUCCESS); 30 return result; 31 } 32 33 /** 34 * 请求成功带返回值 35 * 36 * @param data 37 */ 38 public static Result success(Object data) { 39 Result result = success(); 40 result.setData(data); 41 return result; 42 } 43 44 /** 45 * 请求失败不带返回值 46 * 47 * @param resultCode 48 * @return 49 */ 50 public static Result failure(ResultCode resultCode) { 51 Result result = new Result(); 52 result.setResultCode(resultCode); 53 return result; 54 } 55 56 /** 57 * 请求失败带返回值 58 * 59 * @param resultCode 60 * @param data 61 * @return 62 */ 63 public static Result failure(ResultCode resultCode, Object data) { 64 Result result = new Result(); 65 result.setResultCode(resultCode); 66 result.setData(data); 67 return result; 68 } 69 }