SpringMVC_返回结果统一处理

2.全局统一结果集处理

2.1分析目前写代码存在的问题

  • 查询单个物品时返回单条数据

    {"id":2,"name":"笔记本","type":"电脑","remark":"9成新,8折出售"}
    
  • 查询列表返回列表数据

    [{"id":1,"name":"键盘","type":"电脑外设","remark":"9成新,半价卖"},{"id":2,"name":"笔记本","type":"电脑","remark":"9成新,8折出售"},{"id":3,"name":"鞋子","type":"收藏鞋","remark":"科比签名的,独一无二"},{"id":5,"name":"单元测试","type":"单元测试","remark":"单元测试"}]
    
  • 删除数据返回单个结果

    true
    
  • 目前对于系统而言参数了三种数据类型

    • 不能做到前后端同时开发
    • 前后端的交互很乱
  • 最后处理

    {"data":true}
    {"data":{"id":2,"name":"笔记本","type":"电脑","remark":"9成新,8折出售"}}
    
    
    {
        "code":2000,
        "data":true,
        "msg":"详情"  
    }
    

2.2处理方式

  • 通过定义一个统一结果集处理

    {
        "code":2000,
        "data":true,
        "msg":"详情"  
    }
    
  • 后端实体

    @Data
    public class ResultResp {
        private Integer code;
        private Object data;
        private String msg;
    }
    
  • 后端返回实体最终结果

    @Data
    public class ResultResp {
        private Integer code;
        private Object data;
        private String msg;
    
        public ResultResp(){
        }
    
        public ResultResp(Integer code,Object data){
            this.code = code;
            this.data=data;
        }
    
        public ResultResp(Integer code,Object data,String msg){
            this.code=code;
            this.data=data;
            this.msg=msg;
        }
    
        public static ResultResp success(Integer code,Object data){
            return new ResultResp(code,data);
        }
    }
    
  • 状态码类

    public class Code {
        /**
         * 定义好协议之后,前端和后端统一按照协议执行
         */
        public static final Integer SAVE_OK = 20000;
        public static final Integer SAVE_FAIL = 20001;
    
    
        public static final Integer UPDATE_OK = 20010;
        public static final Integer UPDATE_FAIL = 20011;
    
        public static final Integer DELETE_OK = 20020;
        public static final Integer DELETE_FAIL = 20021;
    
        public static final Integer GET_OK = 20030;
        public static final Integer GET_FAIL = 20031;
    
        public static final Integer PAGE_OK = 20040;
        public static final Integer PAGE_FAIL = 20041;
    }
    
  • 修改控制层返回代码

    • save 方法

      @PostMapping
      public ResultResp save(@RequestBody Item item){
          boolean ret = service.save(item);
          return new ResultResp(ret? Code.SAVE_OK:Code.SAVE_FAIL,ret);
      }
      
    • update 方法

      @PutMapping
      public ResultResp update(@RequestBody Item item){
          boolean ret = service.update(item);
          return new ResultResp(ret? Code.UPDATE_OK:Code.UPDATE_FAIL,ret);
      }
      
    • delete 方法

      @DeleteMapping("/{id}")
      public ResultResp delete(@PathVariable Long id){
          boolean ret = service.delete(id);
          return new ResultResp(ret? Code.DELETE_OK:Code.DELETE_FAIL,ret);
      }
      
    • 单个结果集处理

      @GetMapping("/{id}")
      public ResultResp getById(@PathVariable Long id){
          Item ret = service.getById(id);
          return ResultResp.success(ret==null?Code.GET_FAIL:Code.GET_OK,ret);
      }
      
    • 集合结果集

      @GetMapping
      public ResultResp list(){
          List<Item> ret = service.lists();
          return ResultResp.success(ret==null?Code.PAGE_FAIL:Code.PAGE_OK,ret);
      }
      
  • 最终实现截图

    SpringMVC_返回结果统一处理_第1张图片

2.3前后端联调

  • 保存操作

    handleAdd() {
        console.log("========")
        axios.post("/item", this.formData).then((res) => {
            if (res.data.code == 20000) {
                //关闭新增弹框
                this.dialogFormVisible = false;
                this.$message.success("添加物品成功")
            } else {
                this.$message.error("添加失败")
            }
        }).finally(() => {
            this.getAll();
        })
    },
    
  • 列表查询

    getAll() {
        axios.get("/item",{
                params:{
                    name:this.pagination.queryString
                }
        }).then((res)=>{
            // this.dataList = res.data;
            if(res.data.code == 20040){
                this.dataList = res.data.data;
            }else{
                this.$message.error("加载失败")
            }
        })
    },
    
  • 删除操作

     handleDelete(row) {
        axios.delete("/item/" + row.id).then((res) => {
            if (res.data.code == 20020) {
                this.$message.success("删除物品成功")
            } else {
                this.$message.error("删除失败")
            }
        }).finally(() => {
            this.getAll();
        })
    }
    
  • 编辑操作

    handleEdit() {
        axios.put("/item", this.formData).then((res) => {
            if (res.data.code == 20010) {
                this.dialogFormVisible4Edit = false;
                this.$message.success("编辑物品成功")
            } else {
                this.$message.error("编辑失败")
            }
        }).finally(() => {
            this.getAll();
        })
    },
    
  • 高级查询修改

    • controller

      @GetMapping
          public ResultResp list(@RequestParam(required = false) String name){
              List<Item> ret = service.lists(name);
              return ResultResp.success(ret==null?Code.PAGE_FAIL:Code.PAGE_OK,ret);
          }
      
    • 业务层

      @Override
          public List<Item> lists(String name) {
              if (name != null && !"".equals(name.trim())) {
      
                  return mapper.list(name);
              }
      
              return mapper.listNull();
          }
      
    • mapper 接口

      @Select("select * from item where name like concat('%',#{name},'%')")
      public List<Item> list(String name);
      
      @Select("select * from item ")
      public List<Item> listNull();
      

你可能感兴趣的:(java,后端,spring)