springboot 自定义响应

2023-12-14 01:02:04

自定义响应类是指在开发中,根据业务需求自定义的用于封装接口响应数据的类。通常情况下,一个自定义响应类包含了接口返回的相关信息,如状态码、消息、数据等。

自定义响应类的设计灵活多样,可以根据具体的业务需求进行定义。一般来说,一个自定义响应类应该包括以下属性或方法:

  1. 状态码(Status Code):表示接口调用的状态,如成功、失败、错误等。
  2. 消息(Message):对接口调用结果的描述信息,可以是成功或失败的提示信息。
  3. 数据(Data):接口返回的具体数据。
  4. 其他业务相关属性:根据业务需求,可能还需要包含其他自定义的属性,如分页信息、错误详情等。

通过自定义响应类,可以将接口响应数据按照统一的格式进行封装和返回,方便前端或其他调用方解析和处理。同时,自定义响应类也可以提供更多的灵活性,可以根据具体的业务场景进行定制,满足不同的需求。

结合swagger进行查看

springboot整合swagger-CSDN博客

1.创建maven项目

2.导入依赖


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.cqh</groupId>
    <artifactId>mybatisPlus</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>


    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <swagger.versiion>3.0.0</swagger.versiion>
        <mybatis.plus>3.1.1</mybatis.plus>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>${mybatis.plus}</version>
        </dependency>


        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-boot-starter</artifactId>
            <version>${swagger.versiion}</version>
        </dependency>
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>swagger-bootstrap-ui</artifactId>
            <version>1.9.6</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.plugin</groupId>
            <artifactId>spring-plugin-core</artifactId>
            <version>2.0.0.RELEASE</version>
        </dependency>

    </dependencies>

</project>

3.导入数据库

?

# Host: localhost  (Version 5.7.23-log)
# Date: 2023-12-07 09:43:34
# Generator: MySQL-Front 6.0  (Build 2.20)


#
# Structure for table "account_info"
#

CREATE TABLE `account_info` (
  `account` varchar(255) COLLATE utf8mb4_bin NOT NULL COMMENT '账户名',
  `username` varchar(255) COLLATE utf8mb4_bin NOT NULL COMMENT '用户名',
  `password` varchar(255) COLLATE utf8mb4_bin NOT NULL COMMENT '密码',
  PRIMARY KEY (`account`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin ROW_FORMAT=DYNAMIC COMMENT='账户信息';

#
# Data for table "account_info"
#

INSERT INTO `account_info` VALUES ('admin','admin','9cbf8a4dcb8e30682b927f352d6559a0'),('pep','佩普','9cbf8a4dcb8e30682b927f352d6559a0');

?

4.配置yml

?5.创建实体类

package com.cqh.entity;


import lombok.Data;

@Data
public class AccountInfo {
    private String account;
    private String username;
    private String password;
}

?6.导入自定义响应类

package com.cqh.config;

public final class R<T> {
    private int code;
    private String msg;
    private T data;

    public R() {

    }

    public R(int code) {
        this.code = code;
        this.msg = "";
        this.data = null;
    }

    public R(int code, String msg) {
        this.code = code;
        this.msg = msg;
        this.data = null;
    }

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

    public static  R Success(Object data) {
        return new  R( ResultCodeEnum.SUCCESS.getCode(),  ResultCodeEnum.SUCCESS.getMessage(), data);
    }

    public static  R Success(String message, Object data) {
        return new  R( ResultCodeEnum.SUCCESS.getCode(), message, data);
    }

    public static  R Success() {
        return Success("");
    }

    public static  R Failed(String msg) {
        return new  R( ResultCodeEnum.SYSTEM_EXCEPTION.getCode(), msg);
    }

    public static R Failed() {
        return Failed("Failed");
    }

    public static R Failed(int code, String msg) {
        return new  R(code, msg);
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public boolean succeeded() {
        return getCode() == ResultCodeEnum.SUCCESS.getCode();
    }


    public boolean failed() {
        return getCode() != ResultCodeEnum.SUCCESS.getCode();
    }

}
package com.cqh.config;

import java.util.ArrayList;
import java.util.List;

public enum ResultCodeEnum {

    SUCCESS(100200, "返回成功"),
    SYSTEM_EXCEPTION(100500, "系统异常"),
    REQUEST_PARAM_ERROR(100401, "请求参数错误"),
    REQUEST_OUT_OVERTIME(100408, "请求超时"),
    REQUEST_NOT_FOUND(100404, "请求的资源或服务未找到"),
    REQUEST_LENGTH_LIMIT(100414, "请求URI太长"),
    REQUEST_Format_NOT_SUPPORTED(100415, "请求的格式不支持"),
    TOKEN_EXPIRED_REDIRECT(100302, "token过期,请重新登录"),
    DUPLICATE_KEY_EXCEPTION(100416, "数据已存在,请勿重复操作"),

    INTERFACE_BASIC_INFORMATION_NULL(100001, "接口基本信息为空"),
    INTERFACE_NAME_NULL(100002, "接口名称为空"),
    INTERFACE_SOURCE_NULL(100005, "接口来源为空"),
    INTERFACE_PROTOCOL_NULL(100003, "接口协议为空"),
    INTERFACE_NOT_ENABLED(100123, "接口未启用"),
    INTERFACE_IP_PORT_NULL(100012, "ip和端口为空"),
    INTERFACE_PATH_NULL(100004, "接口路径为空"),
    INTERFACE_REQUEST_METHOD_NULL(100008, "接口请求方式"),
    REQUEST_TIMEOUT(100014, "超时时限为空"),
    REQUEST_PARAM_NULL(100012, "请求参数为空"),
    INTERFACE_BASE_NOT_FOUND(100013, "未找到该条接口基本信息"),
    INTERFACE_SETTING_NOT_FOUND(100015, "未找到该条接口配置信息"),
    INTERFACE_BASE_EXIST(100026, "接口基本信息已存在"),
    INTERFACE_BASE_NOT_EXIST(100025, "接口基本信息不存在"),
    INTERFACE_SETTING_EXIST(100027, "接口配置信息已存在"),
    INTERFACE_SETTING_NOT_EXIST(100028, "接口配置信息不存在"),
    INTERFACE_PATH_ILLEGAL(100009, "接口路径不符合规范"),
    REQUIRED_FIELD_IS_BLANK(100007, "入参必填字段为空: "),
    REQUEST_OUT_API_FAIL(100018, "请求外部接口失败,返回状态码:"),
    REQUEST_OUT_GET_OVERTIME(100019, "GET请求外部接口失败,请求超时"),
    REQUEST_OUT_POST_OVERTIME(100020, "POST请求外部接口失败,请求超时"),
    REQUEST_OUT_PUT_OVERTIME(100021, "PUT请求外部接口失败,请求超时"),
    REQUEST_OUT_DELETE_OVERTIME(100022, "DELETE请求外部接口失败,请求超时"),
    OTHER_METHODS_NOT_SUPPORTED(100023, "现阶段不支持其他请求方式"),
    PARAM_BODY_CONTENT_ERROR(100024, "请求body不是json格式"),
    SPLICING_PARAM_IS_FAIL(100031, "拼接GET请求入参出错,请检查参数"),

    //登录登出模块
    PASSWORD_FAIL(210001, "登录账户或密码错误,请重新输入!"),
    INSUFFICIENT_PERMISSIONS(210002, "用户权限不足"),
    ACCOUNT_NOT_FIND_RESOURCE(210003, "用户未查询到资源"),
    APP_WAS_NOT_QUERIED(210004, "应用id不存在"),
    SIGNATURE_VERIFICATION_FAILED(210005, "验签未通过"),
    RANDOM_CODE_EXPIRED(210006, "随机码已过期"),
    INCORRECT_RANDOM_CODE_VALUE(210007, "随机码值不正确"),
    TOKEN_GENERATION_FAILED(210008, "token 生成失败"),
    NO_TOKEN_PASSED_IN(210009, "未传入 token"),
    NO_USER_FOUND_TOKEN(210009, "token 未查询到用户"),
    TOKEN_VERIFICATION_FAILED(210009, "token 校验失败"),
    ILLEGAL_TOKEN_INFORMATION(210010, "token 信息不匹配"),
    USER_DOES_NOT_EXIST(210011, "用户不存在"),
    SIGN_EXPIRED(210012, "sign 已过期"),
    PASSWORD_VIOLATION(210013, "密码需包含六位及以上字母和数字"),

    //需要跳转登录的code
    NO_REFRESH_PASSED_IN(210019, "未传入 token"),
    NO_REFRESH_USER_FOUND_TOKEN(210019, "token 未查询到用户"),
    REFRESH_VERIFICATION_FAILED(210019, "token 校验失败"),
    JSON_CONVERSION_ERROR(210019, "json转换出错"),
    REFRESH_GENERATION_FAILED(210019, "token 生成失败"),

    NO_LOGIN_STRATEGY(210020, "%s该认证策略不存在"),

    NOT_HAVE_ACCOUNT(202003, "账户不存在"),
    ;

    /**
     * 枚举值
     */
    private final Integer code;

    /**
     * 枚举描述
     */
    private final String message;

    /**
     * 构造一个<code>LocalCacheEnum</code>枚举对象
     *
     * @param code    枚举值
     * @param message 枚举描述
     */
    ResultCodeEnum(Integer code, String message) {
        this.code = code;
        this.message = message;
    }

    /**
     * 获取全部枚举
     *
     * @return List<LocalCacheEnum>
     */
    public static List<ResultCodeEnum> getAllEnum() {
        List<ResultCodeEnum> list = new ArrayList<>();
        for (ResultCodeEnum each : values()) {
            list.add(each);
        }
        return list;
    }

    /**
     * 获取全部枚举值
     *
     * @return List<String>
     */
    public static List<Integer> getAllEnumCode() {
        List<Integer> list = new ArrayList<>();
        for (ResultCodeEnum each : values()) {
            list.add(each.code);
        }
        return list;
    }

    public Integer getCode() {
        return code;
    }

    public String getMessage() {
        return message;
    }

    public <T> R<T> result() {
        return new R(getCode(), getMessage());
    }

    public <T> R<T> result(String message) {
        return new R(getCode(), message);
    }

    /**
     * 将返回码标准的信息 填充到message里面,message必须包含一个%s
     */
    public <T> R<T> resultFillingMessage(String message) {
        return new R(getCode(), String.format(message, getMessage()));
    }

    /**
     * 将message添加到返回码标准的信息后面 再返回{@link R}
     */
    public <T> R<T> resultAppendMessage(String message) {
        return new R(getCode(), getMessage() + message);
    }
}

7.创建service

7.1service实现类

?8.controller控制类

package com.cqh.controller;

import com.cqh.config.R;
import com.cqh.entity.AccountInfo;
import com.cqh.service.AccountInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Api(value = "账户管理",tags = {"账户信息"})
public class AccountController {
    @Autowired
    private AccountInfoService accountService;

    @GetMapping("/findAll")
    @ApiOperation("查询所有账户信息")
    public R<List<AccountInfo>> findAll(){
        List<AccountInfo> list = accountService.list();

        return R.Success(list);
    }


    @GetMapping("/addData/{account}/{username}/{password}")
    @ApiOperation("新增账户信息")
    public R addData(@ApiParam(value ="用户账号") @PathVariable(name = "account",required = true) String account,@ApiParam(value = "用户姓名") @PathVariable(name = "username",required = true) String username,@ApiParam("密码") @PathVariable(name="password",required = true)String password ){
        AccountInfo accountInfo = new AccountInfo();
        accountInfo.setAccount(account);
        accountInfo.setUsername(username);
        accountInfo.setPassword(password);
       accountService.save(accountInfo);
        return R.Success();
    }

}

?9.启动类启动

10.浏览器访问接口

http://localhost:8080/doc.html

?

文章来源:https://blog.csdn.net/qq_67832732/article/details/134822654
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。