目录
为什么需要封装web返回对象
因为SpringMVC的controller层会自动将返回对象封装成json格式返回给客户端,在前后端分离的架构中,后端返回给移动端或者前端的数据最好有固定的格式,由特定的 属性名标记对应的数据。例如 :status 属性代表状态码 , message 属性 为消息内容,date 属性 为 处理后的业务数据。使得前端 获取到的 web 方法的返回结果统一,从而处理更加方便。写代码也会更加顺利。
如何封装返回对象
使用范型
public class DemoResponse<T> {
private Integer code;
private String message;
private T Data;
public DemoResponse(Integer code, String message) {
this.code = code;
this.message = message;
}
// 请求成功才返回数据 更好的灵活性,
public DemoResponse(T data) {
code = 200;
message = "success";
Data = data;
}
private DemoResponse(ExceptionEnum e) {
this.code = e.getCode();
this.message = e.getMessage();
}
// 这里加泛型是因为 有警告 看着难受
public static DemoResponse<String> success() {
return new DemoResponse<>(null);
}
public static <T> DemoResponse<T> success(T data) {
return new DemoResponse<>(data);
}
// 这里加泛型是因为 有警告 看着难受
public static DemoResponse<String> fail() {
// 根据 接口开发 文档 根据实际情况选择 10001
return new DemoResponse<>(10001,"failed");
}
public static DemoResponse<ExceptionEnum> fail(ExceptionEnum e) {
return new DemoResponse<>(e);
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public T getData() {
return Data;
}
public void setData(T data) {
Data = data;
}
}
调用
return new DemoResponse<>(userMap).success();
return new DemoResponse<>(userMap).error("添加失败!");
返回类继承HashMap
package com.example.emos.wx.common.util;
import org.apache.http.HttpStatus;
import java.util.HashMap;
import java.util.Map;
public class R extends HashMap<String, Object> {
public R() {
put("code", HttpStatus.SC_OK);
put("msg", "success");
}
public static R error() {
return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, "未知异常,请联系管理员");
}
public static R error(String msg) {
return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, msg);
}
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 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 ok() {
return new R();
}
public R put(String key, Object value) {
super.put(key, value);
return this;
}
}
调用
return R.ok().put("result", list);
return R.ok();