java 结果集工具类
文章目录
工作中总结的结果集工具类,可灵活增减返回结果字段
工具类:
package com.hy.web.utils;
import java.io.Serializable;
import java.util.HashMap;
/**
* 结果集工具类
*
* @author hy
* @date 2022/7/13 10:46
*/
public class HyResult extends HashMap<String, Object> implements Serializable {
public HyResult() {
}
public HyResult(int code) {
this.setCode(code);
}
public HyResult(int code, String msg) {
this.setCode(code);
this.setMsg(msg);
}
public HyResult(int code, Object data) {
this.setCode(code);
this.setData(data);
}
public HyResult(int code, String msg, Object data) {
this.setCode(code);
this.setMsg(msg);
this.setData(data);
}
public HyResult setCode(int code) {
this.put("code", code);
return this;
}
public HyResult setMsg(String msg) {
this.put("msg", msg);
return this;
}
public HyResult setData(Object data) {
this.put("data", data);
return this;
}
/**
* 成功返回
*
* @return
*/
public static HyResult ok() {
return new HyResult(0);
}
/**
* 默认失败返回
*
* @return
*/
public static HyResult fail() {
return new HyResult(1, "fail");
}
/**
* 自定义msg失败返回
*
* @param msg
* @return
*/
public static HyResult fail(String msg) {
return new HyResult(1, msg);
}
/**
* 自定义code和msg失败返回
*
* @param code
* @param msg
* @return
*/
public static HyResult fail(int code, String msg) {
return new HyResult(code, msg);
}
/**
* 返回数据
*
* @param data
* @return
*/
public static HyResult data(Object data) {
return new HyResult(0, data);
}
}
使用:
/**
* 成功
* @return
*/
@GetMapping("/test1")
public HyResult test1() {
return HyResult.ok();
}
/**
* 失败
* @return
*/
@GetMapping("/test2")
public HyResult test2() {
return HyResult.fail();
}
/**
* 数据
* @return
*/
@GetMapping("/test3")
public HyResult test3() {
return HyResult.data("数据");
}
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论