说明
接口的返回响应,封装成统一的数据格式,再返回给前端。
返回响应,统一封装实体
,数据结构如下。
代码
package com.example.core.model;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.*;
/**
* 返回响应,统一封装实体
*
* @param <T> 数据实体泛型
*/
@Getter
@ToString
@EqualsAndHashCode
@AllArgsConstructor(access = AccessLevel.PRIVATE)
@Schema(name = "返回响应", description = "返回响应,统一封装实体")
public class Result<T> {
@Schema(description = "请求是否成功:true 成功,false 失败", example = "true")
private Boolean success;
@Schema(description = "用户提示", example = "操作成功!")
private String userMessage;
/**
* 错误码<br>
* 调用成功时,为 null。<br>
* 示例:10001
*/
@Schema(description = "错误码")
private Integer errorCode;
/**
* 错误信息<br>
* 调用成功时,为 null。<br>
* 示例:"验证码无效"
*/
@Schema(description = "错误信息")
private String errorMessage;
/**
* 数据实体(泛型)<br>
* 当接口没有返回数据时,为 null。
*/
@Schema(description = "数据实体(泛型)")
private T data;
public static <T> Result<T> success() {
return success(null);
}
public static <T> Result<T> success(T data) {
return new Result<>(true, "操作成功!", null, null, data);
}
public static <T> Result<T> fail(String userMessage, Integer errorCode, String errorMessage) {
return new Result<>(false, userMessage, errorCode, errorMessage, null);
}
}
接口测试
代码
package com.example.web;
import com.example.core.model.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("result")
@Tag(name = "Result")
public class ResultController {
@Operation(summary = "查询 Result<String>")
@Parameter(name = "name", description = "姓名")
@GetMapping("/string")
public Result<String> getResultWithString(@Nullable String name) {
String text = "您好," + name + "!";
return Result.success(text);
}
}