4、springboot3 vue3开发平台-后端-数据封装(返回数据、分页参数、分页数据、全局异常处理)

1. 在support模块引入几个工具类

父pom
在这里插入图片描述
support pom

   		<dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba.fastjson2</groupId>
            <artifactId>fastjson2</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

2. 封装数据

2.1 封装响应码

在这里插入图片描述

package com.ylp.common.constants;

/**
 * 保存响应状态码
 */
public interface HttpStatus {
    /**
     * 操作成功
     */
    public static final int SUCCESS = 200;

    /**
     * 对象创建成功
     */
    public static final int CREATED = 201;

    /**
     * 请求已经被接受
     */
    public static final int ACCEPTED = 202;

    /**
     * 操作已经执行成功,但是没有返回数据
     */
    public static final int NO_CONTENT = 204;

    /**
     * 资源已被移除
     */
    public static final int MOVED_PERM = 301;

    /**
     * 重定向
     */
    public static final int SEE_OTHER = 303;

    /**
     * 资源没有被修改
     */
    public static final int NOT_MODIFIED = 304;

    /**
     * 参数列表错误(缺少,格式不匹配)
     */
    public static final int BAD_REQUEST = 400;

    /**
     * 未授权
     */
    public static final int UNAUTHORIZED = 401;

    /**
     * 访问受限,授权过期
     */
    public static final int FORBIDDEN = 403;

    /**
     * 资源,服务未找到
     */
    public static final int NOT_FOUND = 404;

    /**
     * 不允许的http方法
     */
    public static final int BAD_METHOD = 405;

    /**
     * 资源冲突,或者资源被锁
     */
    public static final int CONFLICT = 409;

    /**
     * 不支持的数据,媒体类型
     */
    public static final int UNSUPPORTED_TYPE = 415;

    /**
     * 系统内部错误
     */
    public static final int ERROR = 500;

    /**
     * 接口未实现
     */
    public static final int NOT_IMPLEMENTED = 501;

    /**
     * 系统警告消息
     */
    public static final int WARN = 601;
}

2.2 封装响应数据类

在这里插入图片描述
注: 要使用OpenApi3注解的话在common模块也需要引入knife4j依赖

package com.ylp.common.response;

import io.swagger.v3.oas.annotations.media.Schema;

@Schema(description = "响应数据")
public class Result<T> {

    /**
     * 状态码 0:成功 1: 失败
     */
    @Schema(description = "状态码")
    private int code;
    /**
     * 返回内容
     */
    @Schema(description = "返回内容")
    private String message;
    /**
     * 数据对象
     */
    @Schema(description = "返回数据")
    private T data;

    public Result(int code, String message, T data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }

    public static <E> Result<E> success() {
        return new Result<>(0, "操作成功", null);
    }

    public static <E> Result<E> success(E data) {
        return new Result<>(0, "操作成功", data);
    }

    public static <E> Result<E> success(String message, E data) {
        return new Result<>(0, message, data);
    }

    public static <E> Result<E> error(String message) {
        return new Result<>(1, message, null);
    }

    public static <E> Result<E> error() {
        return new Result<>(1, "操作失败", null);
    }


}

2.3 分页查询数据封装

在这里插入图片描述

package com.ylp.common.response;

import io.swagger.v3.oas.annotations.media.Schema;

import java.util.List;

@Schema(description = "分页查询数据")
public class PageResult<T> {
    @Schema(description = "分页数据")
    private List<T> list;
    @Schema(description = "数据总条数")
    private long total;

    public PageResult(List<T> data, long total) {
        this.list = data;
        this.total = total;
    }
    public List<T> getList() {
        return list;
    }

    public void setList(List<T> list) {
        this.list = list;
    }

    public long getTotal() {
        return total;
    }

    public void setTotal(long total) {
        this.total = total;
    }
}

2.4 分页参数封装

可继承此类,接受前端分页条件查询参数
在这里插入图片描述

package com.ylp.common.request;

import java.io.Serializable;

public class PageParm implements Serializable {
    // 当前页
    private Long currentPage = 1L;
    // 每页的数据量
    private Long pageSize = 10L;

    public Long getCurrentPage() {
        return currentPage;
    }
    public PageParm() {
    }

    public PageParm(Long currentPage, Long pageSize) {
        this.currentPage = currentPage;
        this.pageSize = pageSize;
    }

    public void setCurrentPage(Long currentPage) {
        this.currentPage = currentPage;
    }

    public Long getPageSize() {
        return pageSize;
    }

    public void setPageSize(Long pageSize) {
        this.pageSize = pageSize;
    }
}

2.5 自定义业务异常

用于业务异常抛出
在这里插入图片描述

package com.ylp.common.exception;

/**
 * 自定义的业务异常。当我们的系统出现异常时,返回该异常给前端
 */
public class ServiceException extends RuntimeException{

    private static final long serialVersionUID = 1L;

    /**
     * 错误码
     */
    private Integer code;

    /**
     * 错误提示
     */
    private String message;
    /**
     * 错误明细,内部调试错误
     */
    private String detailMessage;

    /**
     * 空构造方法,避免反序列化问题
     */
    public ServiceException() {
    }

    public ServiceException(String message) {
        this.message = message;
    }

    public ServiceException(Integer code,String message) {
        this.message = message;
        this.code = code;
    }

    public String getDetailMessage() {
        return detailMessage;
    }

    public String getMessage() {
        return message;
    }

    public Integer getCode() {
        return code;
    }

    public ServiceException setMessage(String message) {
        this.message = message;
        return this;
    }

}

3. 全局异常处理

在support 配置全局异常处理,用于捕获系统异常,防止返回前端报错栈信息及登录拦截信息处理
在这里插入图片描述

package com.ylp.support.config.execption;

import com.ylp.common.exception.ServiceException;
import com.ylp.common.response.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


/**
 * 全局异常处理
 */

@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 业务异常
     */
    @ExceptionHandler(ServiceException.class)
    public Result handleServiceException(ServiceException e)
    {
        log.error(e.getMessage(), e);
        return Result.error(StringUtils.hasLength(e.getMessage()) ? e.getMessage() : "操作失败");
    }

    /**
     * 服务异常
     */
    @ExceptionHandler(Exception.class)
    public Result handlerException(Exception e) {
        log.warn(e.getMessage());
        return Result.error(StringUtils.hasLength(e.getMessage()) ? e.getMessage() : "服务异常");
    }


}

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
好的,我会针对你的问题进一步解答。 在SpringBoot后端的实现中,你需要先建立一个Entity类,用于映射数据库中的表结构。然后,你需要使用Spring Data JPA进行数据访问,可以通过继承JpaRepository接口来实现基本的CRUD操作。在Controller层,你需要定义一个RESTful接口,用于返回数据给前端。例如: ```java @RestController @RequestMapping("/api") public class DataController { @Autowired private DataRepository dataRepository; @GetMapping("/data") public List<Data> getData() { return dataRepository.findAll(); } } ``` 在上述代码中,我们定义了一个GET类型的RESTful接口,用于返回DataRepository中的所有数据。 接下来,我们需要在Vue前端中调用这个接口,获取数据并显示在el-table中。在Vue中,你可以使用axios库来调用后端接口。例如: ```javascript <template> <el-table :data="tableData"> <el-table-column prop="id" label="ID"></el-table-column> <el-table-column prop="name" label="Name"></el-table-column> <el-table-column prop="age" label="Age"></el-table-column> </el-table> </template> <script> import axios from 'axios'; export default { data() { return { tableData: [] }; }, mounted() { axios.get('/api/data').then(response => { this.tableData = response.data; }); } }; </script> ``` 在上述代码中,我们定义了一个el-table组件,并将数据绑定到tableData属性上。在mounted钩子函数中,我们使用axios库调用后端接口,将返回数据赋值给tableData属性。 当页面加载完成后,el-table会自动显示数据。如果后端数据发生变化,你可以通过监听el-table的事件,重新调用后端接口并更新tableData属性,实现数据的动态显示。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不知所云,

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值