type
Post
status
Published
date
Nov 22, 2021
slug
summary
介绍 SpringBoot 前后端分离项目中 项目中常用的两种约定 Controller 消息返回结构方式
tags
项目方案
category
技术分享
icon
password
定义返回 Controller 返回的对象字段和格式,用于统一数据格式,并让 SpringMVC 自动将对象序列化成 JSON 字符串后进行响应

消息结构固定

规定消息结构的三个字段:
  • 状态码
  • 消息
  • 额外数据(响应对象)
public class ApiCommonResponse<T> {    private Integer status;    private String msg;    private T data;    //常用的返回码和消息    private static final int OK_CODE = 10000;    private static final String OK_MSG = "SUCCESS";    //单参构造函数:不传递参数即默认使用成功的code和msg    public ApiCommonResponse() {        this(OK_CODE,OK_MSG);   }    //三参构造函数    public ApiCommonResponse(Integer status, String msg, T data) {        this.status = status;        this.msg = msg;        this.data = data;   }    //双参构造函数    public ApiCommonResponse(Integer status, String msg) {        this.status = status;        this.msg = msg;   }    //getter&setter //返回成功的方法    public static <T> ApiCommonResponse<T> success(){        return new ApiCommonResponse();   }    public static <T> ApiCommonResponse<T> success(T result){        ApiCommonResponse<T> response = new ApiCommonResponse<>();        response.setData(result);        return response;   } //返回失败的方法    public static <T> ApiCommonResponse<T> error(ExceptionEnum ee){        return new ApiCommonResponse<>(ee.getCode(),ee.getMsg());   }    public static <T> ApiCommonResponse<T> error(Integer status,String msg){        return new ApiCommonResponse<>(status,msg);   } }

HashMap 扩展消息结构

不固定消息的字段,继承 hashmap 来实现消息结构的扩展
错误码可以使用 Apache httpcomponents库里的HttpStatus类封装的状态码
public class R extends HashMap<String, Object> { public R() { put("code", HttpStatus.SC_OK); put("msg", "success"); } @Override public R put(String key, Object value) { super.put(key, value); return this; } public static R ok() { return new R(); } public static R ok(String msg) { R r = new R(); r.put("msg", msg); return r; } public static R ok(Map<String, Object> map) { R r = new R(); r.putAll(map); return r; } public static R error(int code, String msg) { R r = new R(); r.put("code", code); r.put("msg", msg); return r; } public static R error(String msg) { return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, msg); } public static R error() { return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, "未知异常,请联系管理员"); } }
hibernate 接口入参校验并查集实现