SpringBoot进阶之统一接口返回信息格式

时间:2021-05-21 16:48:59

1.定义一个返回信息的实体类:

public class Msg<T> {

    /*错误码*/
    private Integer code;

    /*提示信息 */
    private String msg;

    /*具体内容*/
    private  T data;

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }
}

2.在工具类中定义统一的返回信息格式

public class ResultUtil {
    /**
     * 请求成功返回
     * @param object
     * @return
     */
    public static Msg success(Object object){
        Msg msg=new Msg();
        msg.setCode(200);
        msg.setMsg("请求成功");
        msg.setData(object);
        return msg;
    }
    public static Msg success(){
        return success(null);
    }

    public static Msg error(Integer code,String resultmsg){
        Msg msg=new Msg();
        msg.setCode(code);
        msg.setMsg(resultmsg);
        return msg;
    }


}

3.Controller调用

/**
 * 根据id删除
 * @param id
 */
@DeleteMapping(value = "/girls/{id}")
public Msg girlDelete(@PathVariable("id")Integer id){
    girlRepository.delete(id);
    return ResultUtil.success();
}

/**
 * 通过年龄查询
 * @param age
 * @return
 */
@GetMapping(value = "/age/{age}")
public Msg girlListByAge(@PathVariable("age") Integer age){
    return ResultUtil.success(girlRepository.findByAge(age));
}

请求效果图:

SpringBoot进阶之统一接口返回信息格式