统一返回结果集
1.
查看统一返回结果的信息:一般最少4个
Success // 是否正确 boolean
Message // 返回的消息
Code // 状态码
Data // 数据的
2.具体步骤
1、 先创建一个枚举,创建返回成功和失败的变量;
2、 创建返回对象类;
a) 建议要有一个OK的方法,error的方法方便调用;
b) 自定义的message,success,code,data的方法
3.枚举类例子如下:
@Getter
public enum ResultCodeEnum {
SUCCESS(true, 20000,"成功"),
UNKNOWN_REASON(false, 20001, "未知错误"),
BAD_SQL_GRAMMAR(false, 21001, "sql语法错误"),
JSON_PARSE_ERROR(false, 21002, "json解析异常"),
PARAM_ERROR(false, 21003, "参数不正确"),
FILE_UPLOAD_ERROR(false, 21004, "文件上传错误"),
EXCEL_DATA_IMPORT_ERROR(false, 21005, "Excel数据导入错误");
private Boolean success;
private Integer code;
private String message;
private ResultCodeEnum(Boolean success, Integer code, String message) {
this.success = success;
this.code = code;
this.message = message;
}
}
4.统一返回对象类 例子如下:
@Data
@ApiModel(value = "全局统一返回结果")
public class R {
@ApiModelProperty(value = "是否成功")
private Boolean success;
@ApiModelProperty(value = "返回码")
private Integer code;
@ApiModelProperty(value = "返回消息")
private String message;
@ApiModelProperty(value = "返回数据")
private Map<String, Object> data = new HashMap<String, Object>();
private R(){}
public static R ok(){
R r = new R();
r.setSuccess(ResultCodeEnum.SUCCESS.getSuccess());
r.setCode(ResultCodeEnum.SUCCESS.getCode());
r.setMessage(ResultCodeEnum.SUCCESS.getMessage());
return r;
}
public static R error(){
R r = new R();
r.setSuccess(ResultCodeEnum.UNKNOWN_REASON.getSuccess());
r.setCode(ResultCodeEnum.UNKNOWN_REASON.getCode());
r.setMessage(ResultCodeEnum.UNKNOWN_REASON.getMessage());
return r;
}
public static R setResult(ResultCodeEnum resultCodeEnum){
R r = new R();
r.setSuccess(resultCodeEnum.getSuccess());
r.setCode(resultCodeEnum.getCode());
r.setMessage(resultCodeEnum.getMessage());
return r;
}
public R success(Boolean success){
this.setSuccess(success);
return this;
}
public R message(String message){
this.setMessage(message);
return this;
}
public R code(Integer code){
this.setCode(code);
return this;
}
public R data(String key, Object value){
this.data.put(key, value);
return this;
}
public R data(Map<String, Object> map){
this.setData(map);
return this;
}
}
5.测试如下:
/*
* 查询方法
* */
@ApiOperation(value = "person1查询数据")
@ResponseBody
@GetMapping("/selectOnePerson/{id}")
public R selectOnePerson(@ApiParam(name="id", value = "personID", required = true) @PathVariable("id") Integer id) {
try {
Person person = personServer.selectOne(id);
return R.ok().data("person",person);
} catch (Exception e) {
return R.error();
}
}