前后数据传输协议规范

本文介绍了如何在后端开发中规范化API的返回格式,通过创建Result类和Code类来统一处理数据返回,包括成功和失败的场景。在Controller层中,针对增删改查操作,使用Result类包装数据和状态码,确保前端能清晰地理解返回信息。此外,还展示了Service接口及其实现、DAO层和实体类Brand的相关代码示例。
摘要由CSDN通过智能技术生成

在进行增删改操作时,我们通常会返回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;

}

 

项目目录图:


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

白日日白

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

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

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

打赏作者

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

抵扣说明:

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

余额充值