TipsTips响应包装类
CAMELLIA响应包装类
响应包装类(Response Wrapper)是一种设计模式,旨在为API提供一致和结构化的响应格式。这种类通常用于标准化服务器端应用程序与客户端之间的通信,确保所有的API响应都包含必要的元数据和数据内容。
说得通俗点就是把我们后端返回的数据处理一下,让他看起来规范一点,以便于前端处理数据。
1 2 3 4 5 6 7 8 9 10 11 12
| @PostMapping("/users") public List<User> select() { ... return userList; }
@DeleteMapping("/users/{id}") public void deleteUserById(@PathVariable long id) { ... }
...
|
这段代码中,每个返回值都不同。如果不进行包装而直接返回给前端,前端处理起来会很困难。
这时我们可以设置响应包装类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| package com.itheima.pojo;
import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor;
@Data @NoArgsConstructor @AllArgsConstructor public class Result { private Integer code; private String msg; private Object data;
public static Result success(){ return new Result(1,"success",null); } public static Result success(Object data){ return new Result(1,"success",data); } public static Result error(String msg){ return new Result(0,msg,null); } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
| package camellia.common;
import lombok.Data;
import java.io.Serial; import java.io.Serializable;
@Data public class BaseResponse<T> implements Serializable { @Serial private static final long serialVersionUID = 5477638191965981955L;
private int code;
private T data;
private String message;
private String description;
public BaseResponse(int code, T data, String message, String description) { this.code = code; this.data = data; this.message = message; this.description = description; }
public BaseResponse(int code, T data, String message) { this(code, data, message, ""); }
public BaseResponse(int code, T data) { this(code, data, "", ""); }
public BaseResponse(ErrorCode errorCode) { this(errorCode.getCode(), null, errorCode.getMessage(), errorCode.getDescription()); }
}
|
1 2 3 4 5 6 7 8 9 10
| { "code": 200, "data": { "id": 1, "name": "John Doe" }, "message": "Success", "description": "" }
|
1 2 3 4 5 6 7
| { "code": 404, "data": null, "message": "Not Found", "description": "The requested resource was not found." }
|