springboot整合返回数据统一封装

1、MagCode,错误码枚举类

package com.mgx.common.enums;import lombok.*;
import lombok.extern.slf4j.Slf4j;/*** 错误码* @author mgx*/
@Slf4j
@NoArgsConstructor
@AllArgsConstructor
public enum MsgCode {/*** 枚举标识,根据业务类型进行添加*/Code_200("操作成功",200),Code_400("错误请求", 400),Code_401("未授权", 401),Code_402("权限不足,请联系管理员", 402),Code_403("禁止请求", 403),Code_404("找不到相关内容", 404),Code_408("请求超时", 408),Code_410("该资源已删除", 410),Code_413("请求体过大", 413),Code_414("请求URI过长", 414),Code_415("不支持的媒体类型", 415),Code_500("系统错误", 500),Code_501("用户未登录", 501),Code_502("错误网关", 502),Code_503("服务不可用", 503),Code_504("网关超时", 504),Code_505("HTTP版本暂不支持", 505),Code_506("时间格式错误", 506)//自定义提示,Code_2001("参数错误", 2001),Code_2002("传入参数不符合条件", 2002),Code_2003("缺少请求参数", 2003),Code_2004("请求方式错误", 2004),Code_2005("sql语法错误", 2005),Code_2006("数据不存在", 2006),Code_2007("同步失败", 2007),Code_2008("添加失败", 2008),Code_2009("修改失败", 2009),Code_2010("删除失败", 2010),Code_2011("查询失败", 2011),Code_2012("评估失败", 2012),Code_2013("移出黑名单失败",2013),Code_2014("该车辆已在黑名单中",2014),Code_2015("请输入正确的手机号",2015),Code_2016("不支持的编码格式", 2016),Code_2017("不支持的解码格式", 2017),Code_2018("保存失败", 2018);@Getter@Setterprivate String msg;@Getter@Setterprivate Integer code;public static String getMessage(Integer code){MsgCode msgCode;try {msgCode = Enum.valueOf(MsgCode.class, "Code_" + code);} catch (IllegalArgumentException e) {log.error("传入枚举code错误!code:{}",code);return null;}return msgCode.getMsg();}}

2、统一返回结果类

package com.mgx.common.dto;import com.mgx.common.enums.MsgCode;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;import java.io.Serializable;/*** @author mgx*/
@AllArgsConstructor
@NoArgsConstructor
public class Result<T> implements Serializable {private static final long serialVersionUID = 1L;/** 成功与否 */@Getter protected boolean success;/** 结果代码 */@Getter protected Integer code;/** 消息 */@Getter protected String message;/** 标识(方便接口调试) */@Getter @Setterprotected String tag;/** 版本(方便接口调试) */@Getter @Setterprotected String version;/** 结果数据 */@Getter protected T data;/*** 不需指定code和message* @return SuccessBuilder*/public static SuccessBuilder success() {return new SuccessBuilder(Boolean.TRUE, MsgCode.Code_200.getCode(), MsgCode.Code_200.getMsg());}/*** 同时指定code和message* @return FailBuilder*/public static FailBuilder failure() {return new FailBuilder(Boolean.FALSE);}public static class SuccessBuilder {protected boolean success;protected Integer code;protected String message;protected String tag = "mgx";protected String version = "1.0";protected Object data;protected SuccessBuilder(boolean success, Integer code, String message) {this.success = success;this.code = code;this.message = message;}public SuccessBuilder data(Object data) {this.data = data;return this;}@SuppressWarnings("unchecked")public <T> Result<T> build() {return new Result<>(success, code, message, tag, version, (T) data);}}public static class FailBuilder {protected boolean success;protected Integer code;protected String message;protected String tag = "mgx";protected String version = "1.0";protected Object data;protected FailBuilder(boolean success) {this.success = success;}public FailBuilder code(Integer code) {this.code = code;String message = MsgCode.getMessage(code);if(message != null){this.message = message;}return this;}//如果调用code再调用此message方法,此message方法会覆盖code方法中set的messagepublic FailBuilder message(String message) {this.message = message;return this;}public FailBuilder data(Object data) {this.data = data;return this;}@SuppressWarnings("unchecked")public <T> Result<T> build() {return new Result<>(success, code, message, tag, version, (T) data);}}}

3、BooleanResult封装

package com.mgx.common.dto;import lombok.Data;import java.io.Serializable;/*** @author mgx*/
@Data
public class BooleanResult implements Serializable {private Boolean result;private String reason;public static BooleanResult success(){BooleanResult booleanResult = new BooleanResult();booleanResult.setResult(true);return booleanResult;}public static BooleanResult fail(){return fail(null);}public static BooleanResult fail(String reason){BooleanResult booleanResult = new BooleanResult();booleanResult.setResult(false);booleanResult.setReason(reason);return booleanResult;}}

4、结构展示

5、类

package com.mgx.controller;import com.mgx.common.dto.BooleanResult;
import com.mgx.common.dto.Result;
import com.mgx.service.UnifyService;
import com.mgx.vo.param.SaveInfoUserParam;
import com.mgx.vo.result.InfoUserResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.ibatis.annotations.Param;
import org.springframework.web.bind.annotation.*;import javax.annotation.Resource;/*** @author mgx* @date 2023/9/18 3:36 PM*/
@Api(tags = "springboot整合 统一类型结果集")
@RestController
@RequestMapping("/Unify")
public class UnifyController {@Resourceprivate UnifyService unifyService;@ApiOperation("新增")@PostMapping("/add")public Result<BooleanResult> add(@RequestBody SaveInfoUserParam saveInfoUserParam) {return Result.success().data(unifyService.add(saveInfoUserParam)).build();}@ApiOperation("详情")@GetMapping("/detail")public Result<InfoUserResult> detail(@ApiParam("用户信息的ID") @Param("id") Long id) {return Result.success().data(unifyService.detail(id)).build();}@ApiOperation("删除")@DeleteMapping("/delete")public Result<BooleanResult> delete(@ApiParam("用户信息的ID") @Param(value = "id") Long id){return Result.success().data(unifyService.delete(id)).build();}@ApiOperation("更新")@PutMapping("/update")public Result<BooleanResult> update(@RequestBody SaveInfoUserParam saveInfoUserParam){return Result.success().data(unifyService.update(saveInfoUserParam)).build();}}
package com.mgx.service;import com.mgx.common.dto.BooleanResult;
import com.mgx.vo.param.SaveInfoUserParam;
import com.mgx.vo.result.InfoUserResult;/*** @author mgx* @date 2023/9/18 3:38 PM*/
public interface UnifyService {BooleanResult add(SaveInfoUserParam saveInfoUserParam);InfoUserResult detail(Long id);BooleanResult delete(Long id);BooleanResult update(SaveInfoUserParam saveInfoUserParam);}
package com.mgx.service.impl;import com.mgx.common.dto.BooleanResult;
import com.mgx.entity.InfoUser;
import com.mgx.mapper.InfoUserMapper;
import com.mgx.service.UnifyService;
import com.mgx.utils.BeanUtil;
import com.mgx.vo.param.SaveInfoUserParam;
import com.mgx.vo.result.InfoUserResult;
import org.springframework.stereotype.Service;import javax.annotation.Resource;
import java.util.Objects;/*** @author mgx* @date 2023/9/18 3:38 PM*/
@Service
public class UnifyServiceImpl implements UnifyService {@Resourceprivate InfoUserMapper infoUserMapper;@Overridepublic BooleanResult add(SaveInfoUserParam saveInfoUserParam) {InfoUser infoUser = BeanUtil.map(saveInfoUserParam,InfoUser.class);int addRow = infoUserMapper.insert(infoUser);if (addRow < 1){return BooleanResult.fail();}return BooleanResult.success();}@Overridepublic InfoUserResult detail(Long id) {InfoUser infoUser = infoUserMapper.selectByPrimaryKey(id);if (Objects.isNull(infoUser)){throw new RuntimeException("数据不存在");}return BeanUtil.map(infoUser,InfoUserResult.class);}@Overridepublic BooleanResult delete(Long id) {InfoUser infoUser = infoUserMapper.selectByPrimaryKey(id);if (Objects.isNull(infoUser)){throw new RuntimeException("数据不存在");}int deleteRow = infoUserMapper.deleteByPrimaryKey(id);if (deleteRow<1){return BooleanResult.fail();}return BooleanResult.success();}@Overridepublic BooleanResult update(SaveInfoUserParam saveInfoUserParam) {InfoUser queryInfoUser = infoUserMapper.selectByPrimaryKey(saveInfoUserParam.getId());if (Objects.isNull(queryInfoUser)){throw new RuntimeException("数据不存在");}InfoUser infoUser = BeanUtil.map(saveInfoUserParam,InfoUser.class);int updateRow = infoUserMapper.updateByPrimaryKeySelective(infoUser);if (updateRow<1){return BooleanResult.fail();}return BooleanResult.success();}
}
package com.mgx.utils;import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.*;/*** @author mgx*/
public class BeanUtil {public BeanUtil() {}public static <T> T map(Object source, Class<T> target) {if (null == source) {return null;} else {T t = BeanUtils.instantiateClass(target);BeanUtils.copyProperties(source, t);return t;}}public static <T> List<T> mapList(Collection<?> sourceList, Class<T> target) {if (sourceList == null) {return null;} else {List<T> destinationList = new ArrayList<>();for (Object sourceObject : sourceList) {T newObj = map(sourceObject, target);destinationList.add(newObj);}return destinationList;}}public static void copyProperties(Object source, Object target, String... ignoreProperties) {if (null != source && null != target) {BeanUtils.copyProperties(source, target, ignoreProperties);}}public static <T> T convert(Object source, Class<T> targetClass) {if (source == null) {return null;} else {try {T result = targetClass.newInstance();copyProperties(source, result);return result;} catch (IllegalAccessException | BeansException | InstantiationException var3) {throw new RuntimeException(var3);}}}public static void copyProperties(Object source, Object target) throws BeansException {BeanUtils.copyProperties(source, target);if (target instanceof ConversionCustomizble) {((ConversionCustomizble) target).convertOthers(source);}}public interface ConversionCustomizble {void convertOthers(Object var1);}public static Map<String, Object> beanToMap(Object beanObj) {if (Objects.isNull(beanObj)) {return null;}Map<String, Object> map = new HashMap<>();try {BeanInfo beanInfo = Introspector.getBeanInfo(beanObj.getClass());PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();for (PropertyDescriptor property : propertyDescriptors) {String key = property.getName();if (key.compareToIgnoreCase("class") == 0) {continue;}Method getter = property.getReadMethod();Object value = Objects.isNull(getter) ? null : getter.invoke(beanObj);map.put(key, value);}return map;} catch (Exception ex) {throw new RuntimeException(ex);}}public static <T> T mapToBean(Map<String, Object> map, Class<T> beanClass) {if (MapUtils.isEmpty(map)) {return null;}try {T t = beanClass.newInstance();BeanInfo beanInfo = Introspector.getBeanInfo(t.getClass());PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();for (PropertyDescriptor property : propertyDescriptors) {Method setter = property.getWriteMethod();if (Objects.nonNull(setter)) {setter.invoke(t, map.get(property.getName()));}}return t;} catch (Exception ex) {throw new RuntimeException(ex);}}}

6、测试

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.xdnf.cn/news/140733.html

如若内容造成侵权/违法违规/事实不符,请联系一条长河网进行投诉反馈,一经查实,立即删除!

相关文章

阻塞队列-生产者消费者模型

阻塞队列介绍标准库阻塞队列使用基于阻塞队列的简单生产者消费者模型。实现一个简单型阻塞队列 &#xff08;基于数组实现&#xff09; 阻塞队列介绍 不要和之前学多线程的就绪队列搞混&#xff1b; 阻塞队列&#xff1a;也是一个队列&#xff0c;先进先出。带有特殊的功能 &…

Learn Prompt-提供示例

目前我们与 ChatGPT 交流的主要形式是文字。提示除了指令问题的形式外&#xff0c;还可以包含例子。特别是当我们需要具体的输出时&#xff0c;提供例子可以省去我们对具体任务的解释&#xff0c;帮助ChatGPT更好地理解我们的确切需求&#xff0c;从而提供更准确&#xff0c;更…

【数据结构】哈希应用——位图、布隆过滤器

文章目录 一、位图1.基本概念2.基本实现3.基本应用3.1 找100亿个整数只出现一次的数3.2 两个文件分别有100亿整数&#xff0c;1G内存&#xff0c;求交集 二、布隆过滤器1、基本实现2、基本应用2.1过滤一部分的数据2.2 两个文件&#xff0c;分别100亿个查询&#xff0c;1G内存&a…

[Linux入门]---管理者操作系统

文章目录 1.操作系统概念2.设计操作系统的目的3.操作系统如何进行管理系统调用和库函数概念 1.操作系统概念 任何计算机系统都包含一个基本的程序集合&#xff0c;称为操作系统(OS)。笼统的理解&#xff0c;操作系统包括&#xff1a; 内核&#xff08;进程管理&#xff0c;内存…

C# OpenCvSharp Yolov8 Detect 目标检测

效果 项目 代码 using OpenCvSharp; using OpenCvSharp.Dnn; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms;namespace Open…

索引(含B树、B+树)

1、索引&#xff08;index&#xff09; 索引是在数据库表的字段上添加的&#xff0c;是为了提高查询效率存在的一种机制。 一张表的一个字段可以添加一个索引&#xff0c;当然&#xff0c;多个字段联合起来也可以添加索引。 索引相当于一本书的目录&#xff0c;是为了缩小扫描…

Avl树(有详细图解)

目录 介绍 引入 概念 特点 模拟实现 思路 插入 旋转 左旋 无子树 有子树 右旋 无子树 有子树 左右旋 引入(也就是有子树版本的抽象图解) 解决方法(也就是左右旋) 总结 无子树(也就是curright的位置就是newnode) 有子树 模型高度解释 旋转 更新三个…

深度学习修炼(二)全连接神经网络 | Softmax,交叉熵损失函数 优化AdaGrad,RMSProp等 对抗过拟合 全攻略

文章目录 1 多层感知机&#xff08;全连接神经网络&#xff09;1.1 表示1.2 基本概念1.3 必要组成—激活函数1.4 网络结构设计 2 损失函数2.1 SOFTMAX操作2.2 交叉熵损失函数 3 优化3.1 求导计算过于复杂&#xff1f;3.2 链式法则导致的问题&#xff1f;3.3 梯度下降算法的改进…

八大排序(二)快速排序

一、快速排序的思想 快速排序是Hoare于1962年提出的一种二叉树结构的交换排序方法&#xff0c;其基本思想为&#xff1a;任取待排序元素序列中的某元素作为基准值&#xff0c;按照该排序码将待排序集合分割成两子序列&#xff0c;左子序列中所有元素均小于基准值&#xff0c;右…

免费的AI写作软件-智能AI写作工具

我们要谈的话题是AI写作&#xff0c;尤其是免费AI写作&#xff0c;以及147SEOAI写作免费工具。您是否曾经为了创作文章而感到煞费苦心&#xff1f;是否一直在寻找一种能够轻松生成高质量文章的方法&#xff1f; 147GPT批量文章生成工具​www.147seo.com/post/2801.html​编辑ht…

Flink TaskManger 内存计算实战

Flink TaskManager内存计算图 计算实例 案例一、假设Task Process内存4GB。 taskmanager.memory.process.size4096m 先排减JVM内存。 JVM Metaspace 固定内存 256mJVM Overhead 固定比例 process * 0.1 4096 * 0.1 410m 得到 Total Flink Memory 4096-256-410 3430m 计…

求生之路2服务器搭建插件安装及详细的游戏参数配置教程windows

求生之路2服务器搭建插件安装及详细的游戏参数配置教程windows 大家好我是艾西&#xff0c;最近研究了下 l4d2&#xff08;求生之路2&#xff09;这款游戏的搭建以及架设过程。今天就给喜欢l4d2这款游戏的小伙伴们分享下怎么搭建架设一个自己的服务器。毕竟自己当服主是热爱游…

华为云云耀云服务器L实例评测|redis漏洞回顾 MySQL数据安全解决 搭建主从集群MySQL 相关设置

前言 最近华为云云耀云服务器L实例上新&#xff0c;也搞了一台来玩&#xff0c;期间遇到过MySQL数据库被攻击的情况&#xff0c;数据丢失&#xff0c;还好我有几份备份&#xff0c;没有造成太大的损失&#xff1b;后来有发现Redis数据库被攻击的情况&#xff0c;加入了redis密…

基于springboot+vue的校园外卖服务系统

博主主页&#xff1a;猫头鹰源码 博主简介&#xff1a;Java领域优质创作者、CSDN博客专家、公司架构师、全网粉丝5万、专注Java技术领域和毕业设计项目实战 主要内容&#xff1a;毕业设计(Javaweb项目|小程序等)、简历模板、学习资料、面试题库、技术咨询 文末联系获取 项目介绍…

【Vue+Element-UI】实现登陆注册界面及axios之get、post请求登录功能实现、跨域问题的解决

目录 一、实现登陆注册界面 1、前期准备 2、登录静态页实现 2.1、创建Vue组件 2.2、静态页面实现 2.3、配置路由 2.4、更改App.vue样式 2.5、效果 3、注册静态页实现 3.1、静态页面实现 3.2、配置路由 3.3、效果 二、axios 1、前期准备 1.1、准备项目 1.2、安装…

原生HTML实现marquee向上滚动效果

实现原理&#xff1a;借助CSS3中animation动画以及原生JS克隆API <!DOCTYPE html> <html lang"en"><head><meta charset"UTF-8" /><meta name"viewport" content"widthdevice-width, initial-scale1.0" /…

Northstar 量化平台

基于 B/S 架构、可替代付费商业软件的一站式量化交易平台。具备历史回放、策略研发、模拟交易、实盘交易等功能。兼顾全自动与半自动的使用场景。 已对接国内期货股票、外盘美股港股。 面向程序员的量化交易软件&#xff0c;用于期货、股票、外汇、炒币等多种交易场景&#xff…

OpenCV中的HoughLines函数和HoughLinesP函数到底有什么区别?

一、简述 基于OpenCV进行直线检测可以使用HoughLines和HoughLinesP函数完成的。这两个函数之间的唯一区别在于,第一个函数使用标准霍夫变换,第二个函数使用概率霍夫变换(因此名称为 P)。概率版本之所以如此,是因为它仅分析点的子集并估计这些点都属于同一条线的概率。此实…

php文件上传功能(文件上传)

实现文件上传是Web开发中常用的功能之一&#xff0c;而PHP也是支持文件上传的。那么&#xff0c;下面我们就来介绍一下常用的PHP实现文件上传的方法。 使用HTML表单实现文件上传 HTML表单是Web开发中最基本的元素之一&#xff0c;它可以接收用户输入的数据&#xff0c;并通过…