栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot返回值封装

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot返回值封装

前提:SpringBoot整合MyBatis
为了后台返回值统一格式,在util包中创建Result类将返回值封装

public class Result  {

    private int code;       // 状态码
    private String msg;     // 返回的信息
    private T data;         // 返回的数据

    
    public static  Result success(T data){
        return new Result(data);
    }

    
    public static  Result success(){
        return new Result();
    }

    
    public static  Result error(String msg){
        return new Result(msg);
    }

    
    public static  Result error(){
        return new Result("error");
    }

    private Result(T data) {
        this.code = 200;
        this.msg = "success";
        this.data = data;
    }

    private Result() {
        this.code = 200;
        this.msg = "success";
    }

    private Result(String msg) {
        this.code = 400;
        this.msg = msg;
    }

    public int getCode() {
        return code;
    }

    public String getMsg() {
        return msg;
    }

    public T getData() {
        return data;
    }

}

而控制层的getAll方法的返回类型等要改为:

@GetMapping("/getAll")
public Result getAll() {
	return Result.success(service.getAll());
}

此时用Postman访问http://localhost:8080/student/getAll得到的结果如下:

当然也可以在封装一个常用异常状态参数的类Error(静态异常可以根据项目自由定义)

public class Error {
    private int code;		// 状态码
    private String msg;		// 返回的信息

    private Error(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    // 静态常用异常
    public static Error ERROR_1 = new Error(400,"异常类型一");
    public static Error ERROR_2 = new Error(500,"异常类型二");

    public int getCode() {
        return code;
    }

    public String getMsg() {
        return msg;
    }
}

然后在Result类中添加如下方法:

public static  Result error(Error error){
    return new Result(error);
}

private Result(Error error) {
    if (error == null){
        return ;
    }
    this.code = error.getCode();
    this.msg = error.getMsg();
}

使用:

@GetMapping("/getError")
public Result getError() {
    return Result.error(ERROR_1);
}

访问http://localhost:8080/student/getError

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/770999.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号