当前位置: 首页 > news >正文

前后数据传输协议规范

在进行增删改操作时,我们通常会返回true或false来表示是否查询成功

在进行查询单条数据时,我们通常返回一个json串对应当前查询数据

在进行查询全部数据时,我们通常返回一个json数组

这样就出现了一个问题:返回的数据种类太多没有一个统一的格式,前端无法清楚的获取当前返回数据的类种类。

为了解决这种现象,我们可以自己规定一个统一的返回格式

data:存放数据层返回的数据

code:告知前端调用了何种方法

msg:告知用户查询结果 

在controller层里新建一个Result类,用来规定统一返回格式

在新建一个Code类,规定各种请求方法的状态码

package com.brrbaii.controller;

public class Code {
    //请求成功
    public static final Integer SAVE_OK = 20011;
    public static final Integer DELETE_OK = 20021;
    public static final Integer UPDATE_OK = 20031;
    public static final Integer SELECT_OK = 20041;

    //请求失败
    public static final Integer SAVE_ERR = 20010;
    public static final Integer DELETE_ERR = 20020;
    public static final Integer UPDATE_ERR = 20030;
    public static final Integer SELECT_ERR = 20040;
}

我们在controller里将所有的方法的返回类型都修改为Result类

将数据层的返回结果作为data参数

判断请求类型的操作状态码获取code

将code和data两个数据作为构造器参数构造Result对象,并将该对象返回成一个我们定义的规范的统一的Json格式

 附上完整代码

Controller层:

package com.brrbaii.controller;

import com.brrbaii.pojo.Brand;
import com.brrbaii.service.BrandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.awt.print.Book;
import java.util.List;

@RestController
@RequestMapping("/brands")
public class BrandController {
    @Autowired
    private BrandService brandService;
    @GetMapping
    public Result getAll(){
        List<Brand> brands = brandService.selectAll();
        Integer code = checkMesg(brands) ? Code.SELECT_OK : Code.SELECT_ERR;
        return new Result(code,brands);
    }

    @GetMapping("/{Id}")
    public Result getById(@PathVariable Integer Id){
        Brand brand = brandService.selectById(Id);
        Integer code = checkMesg(brand) ? Code.SELECT_OK : Code.SELECT_ERR;
        String msg = checkMesg(brand) ? "查询成功": "查询失败";
        return new Result(code,brand,msg);
    }

    @PostMapping
    public Result save(@RequestBody Brand brand){
        boolean flag = brandService.save(brand);
        Integer code = flag ? Code.SAVE_OK : Code.SAVE_ERR;
        return new Result(code,flag);
    }

    @DeleteMapping("/{Id}")
    public Result delete(@PathVariable Integer Id){
        boolean flag = brandService.delete(Id);
        Integer code = flag ? Code.DELETE_OK : Code.DELETE_ERR;
        return new Result(code,flag);
    }

    @PutMapping()
    public Result update(@RequestBody Brand brand){
        boolean flag = brandService.updateById(brand);
        Integer code = flag ? Code.UPDATE_OK : Code.UPDATE_ERR;
        return new Result(code,flag);
    }

    public boolean checkMesg(Object o){
        return o != null ? true : false;
    }

}

Service接口:

package com.brrbaii.service;

import com.brrbaii.pojo.Brand;

import java.util.List;

public interface BrandService {

    List<Brand> selectAll();

    Brand selectById(Integer Id);

    boolean save(Brand brand);

    boolean delete(Integer Id);

    boolean updateById(Brand brand);
}

Service实现类

package com.brrbaii.service.Imp;

import com.brrbaii.dao.BrandDao;
import com.brrbaii.pojo.Brand;
import com.brrbaii.service.BrandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BrandServiceImp implements BrandService {

    @Autowired
    private BrandDao brandDao;

    @Override
    public List<Brand> selectAll() {
        List<Brand> brands = brandDao.selectAll();
        return brands;
    }

    @Override
    public Brand selectById(Integer Id) {
        Brand brand = brandDao.selectById(Id);
        return brand;
    }

    @Override
    public boolean save(Brand brand){
        return brandDao.save(brand);
    }

    @Override
    public boolean delete(Integer Id) {
        return brandDao.deleteById(Id);
    }

    @Override
    public boolean updateById(Brand brand) {
        return brandDao.updateById(brand);
    }
}

 Dao层:

package com.brrbaii.dao;

import com.brrbaii.pojo.Brand;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.ResultMap;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface BrandDao {

    @Select("select * from tb_brand")
    @ResultMap("BrandResult")
    List<Brand> selectAll();

    @Select("select * from tb_brand where id = #{Id}")
    @ResultMap("BrandResult")
    Brand selectById(Integer Id);

    @Delete("delete from tb_brand where id = #{Id}")
    boolean deleteById(Integer Id);


    boolean save(Brand brand);

    boolean updateById(Brand brand);
}

BrandDao.xml(用来写复杂的sql语句):

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.brrbaii.dao.BrandDao">
    <resultMap id="BrandResult" type="brand">
        <result column="brand_name" property="brandName" />
        <result column="company_name" property="companyName" />
    </resultMap>

    <insert id="save">
        insert into
            tb_brand
        values
           (null, #{brandName}, #{companyName}, #{ordered}, #{description}, #{status})
    </insert>

    <update id="updateById">
        update tb_brand
        <set>
            <if test="brandName!=null and brandName!= ''">
                brand_name = #{brandName},
            </if>
            <if test="companyName!=null and companyName!= ''">
                company_name = #{companyName},
            </if>
            <if test="description!=null and description!= ''">
                description = #{description},
            </if>
            <if test="ordered!=null and ordered!= ''">
                ordered = #{ordered},
            </if>
            <if test="status!=null and status!= ''">
                status = #{status},
            </if>
        </set>
        where id = #{id}

    </update>

</mapper>

POJO实体类:

@Data
@NoArgsConstructor
@Getter
@Setter
@ToString
public class Brand {
    private int id;
    private String brandName;
    private String companyName;
    private int ordered;
    private String description;
    private int status;

}

 

项目目录图:


相关文章:

  • Unions
  • 基于springboot的地质灾害应急管理系统
  • Structures
  • 向量数据库入坑指南:聊聊来自元宇宙大厂 Meta 的相似度检索技术 Faiss
  • 电子邮件营销新趋势-自动化
  • ICT产业关联效应的国际比较——基于投入产出的分析
  • 【algorithm】算法学习----堆
  • Q_ENUM Q_ENUMS Q_ENUM_NS Q_FLAG Q_FLAGS Q_FLAG_NS
  • 国外5G行业应用产业政策分析及对我国的启示
  • 【C语言】文件输入输出操作
  • 【教3妹学算法-每日一题】竞赛题:6171. 和相等的子数组
  • 遗传算法GA求解非连续函数问题
  • 【电商营销】为什么需要从获取客户转向留住客户
  • 实战讲解Redis基础数据类型List增删改查(带Java源码)
  • 分布式消息队列RocketMQ介绍
  • 【Amaple教程】5. 插件
  • 【Under-the-hood-ReactJS-Part0】React源码解读
  • 8年软件测试工程师感悟——写给还在迷茫中的朋友
  • C++回声服务器_9-epoll边缘触发模式版本服务器
  • ERLANG 网工修炼笔记 ---- UDP
  • java B2B2C 源码多租户电子商城系统-Kafka基本使用介绍
  • java多线程
  • magento2项目上线注意事项
  • Markdown 语法简单说明
  • nginx 配置多 域名 + 多 https
  • Spring Boot快速入门(一):Hello Spring Boot
  • SpringCloud(第 039 篇)链接Mysql数据库,通过JpaRepository编写数据库访问
  • Terraform入门 - 1. 安装Terraform
  • webpack项目中使用grunt监听文件变动自动打包编译
  • web标准化(下)
  • 区块链共识机制优缺点对比都是什么
  • 日剧·日综资源集合(建议收藏)
  • 使用前端开发工具包WijmoJS - 创建自定义DropDownTree控件(包含源代码)
  • 原生 js 实现移动端 Touch 滑动反弹
  • 在Docker Swarm上部署Apache Storm:第1部分
  • No resource identifier found for attribute,RxJava之zip操作符
  • 曜石科技宣布获得千万级天使轮投资,全方面布局电竞产业链 ...
  • # .NET Framework中使用命名管道进行进程间通信
  • # 睡眠3秒_床上这样睡觉的人,睡眠质量多半不好
  • (04)odoo视图操作
  • (9)YOLO-Pose:使用对象关键点相似性损失增强多人姿态估计的增强版YOLO
  • (AtCoder Beginner Contest 340) -- F - S = 1 -- 题解
  • (C++17) std算法之执行策略 execution
  • (vue)页面文件上传获取:action地址
  • (附源码)spring boot校园健康监测管理系统 毕业设计 151047
  • (附源码)springboot人体健康检测微信小程序 毕业设计 012142
  • (附源码)计算机毕业设计SSM保险客户管理系统
  • **PHP二维数组遍历时同时赋值
  • .bat批处理(一):@echo off
  • .net core 6 集成和使用 mongodb
  • .net使用excel的cells对象没有value方法——学习.net的Excel工作表问题
  • 。Net下Windows服务程序开发疑惑
  • [2013][note]通过石墨烯调谐用于开关、传感的动态可重构Fano超——
  • [2019.3.20]BZOJ4573 [Zjoi2016]大森林
  • [C#]C#学习笔记-CIL和动态程序集