24.10.12

理解RESTful API。
学习Spring Boot如何创建REST接口。

RESTful API 是应用程序接口 (API) 的一种架构风格,它使用 HTTP 请求来访问和使用数据。该数据可用于 GET、PUT、POST 和 DELETE 数据类型,这些数据类型是指有关资源的操作的读取、更新、创建和删除。
RESTful API(也称为 RESTful Web 服务或 REST API)基于表示状态传输 (REST),它是一种架构风格和经常用于 Web 服务开发的通信方法。

package stdu.rongchuang.common.core.domain;

import java.io.Serial;
import java.io.Serializable;

/**
 * 通用响应信息类,包含状态码、消息和数据
 *
 * @param <T> 响应的数据类型
 */
public class R<T> implements Serializable {
    @Serial
    private static final long serialVersionUID = 1L;

    /** 成功状态码 */
    public static final int SUCCESS = 0;
    /** 失败状态码 */
    public static final int FAIL = 500;

    private int code;
    private String msg;
    private T data;

    private R(int code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    // 快捷的成功方法
    public static <T> R<T> ok() {
        return new R<>(SUCCESS, "操作成功", null);
    }

    public static <T> R<T> ok(T data) {
        return new R<>(SUCCESS, "操作成功", data);
    }

    public static <T> R<T> ok(T data, String msg) {
        return new R<>(SUCCESS, msg, data);
    }

    // 快捷的失败方法
    public static <T> R<T> fail() {
        return new R<>(FAIL, "操作失败", null);
    }

    public static <T> R<T> fail(String msg) {
        return new R<>(FAIL, msg, null);
    }

    public static <T> R<T> fail(T data) {
        return new R<>(FAIL, "操作失败", data);
    }

    public static <T> R<T> fail(T data, String msg) {
        return new R<>(FAIL, msg, data);
    }

    public static <T> R<T> fail(int code, String msg) {
        return new R<>(code, msg, null);
    }

    // 成功和失败的状态判断方法
    public static <T> boolean isError(R<T> response) {
        return !isSuccess(response);
    }

    public static <T> boolean isSuccess(R<T> response) {
        return response != null && response.code == SUCCESS;
    }

    // Getters 和 Setters
    public int getCode() {
        return code;
    }

    public String getMsg() {
        return msg;
    }

    public T getData() {
        return data;
    }

    // 方便链式调用的 setter 方法
    public R<T> setCode(int code) {
        this.code = code;
        return this;
    }

    public R<T> setMsg(String msg) {
        this.msg = msg;
        return this;
    }

    public R<T> setData(T data) {
        this.data = data;
        return this;
    }
}

posted @ 2024-10-14 21:01  起名字真难_qmz  阅读(21)  评论(0)    收藏  举报