欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

前后端分离Java统一响应返回格式

程序员文章站 2022-06-19 14:58:23
一共需要两个类,一个专门用来存储返回的状态码,一个专门用来存储返回结果ResultCode类public class ResultCode { public static Integer SUCCESS = 200; public static Integer ERROR = 500; public static Integer FORBIDDEN = 403; public static Integer UNAUTHORIZED = 401;}Resul....

一共需要两个类,一个专门用来存储返回的状态码,一个专门用来存储返回结果

ResultCode类

public class ResultCode {
    public static Integer SUCCESS = 200;

    public static Integer ERROR = 500;

    public static Integer FORBIDDEN = 403;

    public static Integer UNAUTHORIZED = 401;
}

Result类

@Data //lombok注解
public class Result {

    //返回码
    private Integer code;

    //返回消息
    private String message;

    //返回数据
    private Map<String, Object> data = new HashMap<String, Object>();

    public Result(){}

    public Result message(String message){
        this.setMessage(message);
        return this;
    }

    public Result code(Integer code){
        this.setCode(code);
        return this;
    }
    
    public Result data(String key, Object value){
        this.data.put(key, value);
        return this;
    }

    public Result data(Map<String, Object> map){
        this.setData(map);
        return this;
    }
}

使用示例

	@RequestMapping("/get")
    public Result get(){
        HashMap map = new HashMap();
        map.put("username","admin");
        map.put("password","123456");
        Result r = new Result();
        r.code(ResultCode.SUCCESS).message("成功访问").data(map);
        return r;
    }

本文地址:https://blog.csdn.net/mengxianglong123/article/details/112235788