1、自定义返回的code以及msg(可以增加新的)
package cn.web959.vo;
/**
* Title: ResultEnum
* @author: gaodeqiang
* @date 2018年12月17日
* @version V1.0
* Description: 返回值封装
*/
public enum ResultEnum {
SUCCESS("200", "操作成功"),
ERROR("500", "操作失败"),
WAIT("1111", "正在处理结果");
private String code;
private String msg;
ResultEnum(String code, String msg) {
this.code = code;
this.msg = msg;
}
public int getCode() {
return Integer.parseInt(code);
}
public String getMsg() {
return msg;
}
}
2、返回值封装(原理是Map集合的一个返回)
package cn.web959.vo;
import java.io.Serializable;
import java.util.HashMap;
/**
* @author: gaodeqiang
* @date 2018年8月15日
* @version V1.0
* @Description: 结果集
*/
public class R implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private int code;
private String msg;
private Object data;
/**
* @return the code
*/
public int getCode() {
return code;
}
/**
* @param code the code to set
*/
public void setCode(int code) {
this.code = code;
}
/**
* @return the msg
*/
public String getMsg() {
return msg;
}
/**
* @param msg the msg to set
*/
public void setMsg(String msg) {
this.msg = msg;
}
/**
* @return the data
*/
public Object getData() {
return data;
}
/**
* @param data the data to set
*/
public void setData(Object data) {
this.data = data;
}
public static R ok(String msg) {
return new R(msg);
}
public static R ok(String msg, Object data) {
return new R(ResultEnum.SUCCESS.getCode(), msg, data);
}
public static R ok(int code,String msg,Object data) {
return new R(code, msg, data);
}
public static R ok(int code,String msg) {
return new R(code, msg);
}
public static R error(String msg) {
return new R(ResultEnum.ERROR.getCode(),msg);
}
public static R error(String msg,Object data) {
return new R(ResultEnum.ERROR.getCode(), msg, data);
}
public static R error(int code,String msg) {
return new R(code, msg);
}
private R(Object data) {
this.code = ResultEnum.SUCCESS.getCode();
this.msg = ResultEnum.SUCCESS.getMsg();
this.data = data;
}
private R(String msg) {
this.code = ResultEnum.SUCCESS.getCode();
this.data = new HashMap<>();
this.msg = msg;
}
private R(int code, String msg) {
this.code = code;
this.data = new HashMap<>();
this.msg = msg;
}
private R(int code, String msg, Object data) {
this.code = code;
this.msg = msg;
this.data = data;
}
}
使用方式:
@GetMapping("/test")
public R test() {
Map<String, String> map=new HashMap<String, String>();
map.put("test", "test");
//code、msg和data是必有值。返回为data数据为一个json对象,对象的key和value为map的key和value
return R.ok("获取成功",map);
List<String> list=new ArrayList<>();
list.add("test");
//返回值中data是一个数组,数组中数据是list中数据
return R.ok("获取成功",list);
//返回值中data是一个空对象
return R.ok("获取成功");
//R.error()支持上述所有操作
}
示例: