• Spring Boot(Vue3+ElementPlus+Axios+MyBatisPlus+Spring Boot 前后端分离)【七】


    😀前言
    本篇博文是关于Spring Boot(Vue3+ElementPlus+Axios+MyBatisPlus+Spring Boot 前后端分离)【七】,希望你能够喜欢

    🏠个人主页晨犀主页
    🧑个人简介:大家好,我是晨犀,希望我的文章可以帮助到大家,您的满意是我的动力😉😉

    💕欢迎大家:这里是CSDN,我总结知识的地方,欢迎来到我的博客,感谢大家的观看🥰
    如果文章有什么需要改进的地方还请大佬不吝赐教 先在此感谢啦😊

    Spring Boot(Vue3+ElementPlus+Axios+MyBatisPlus+Spring Boot 前后端分离)【七】

    实现功能12-家居表单后端校验

    需求分析/图解

    1. 为什么前端校验了,后端还需要校验?-使用Postman 添加数据, 破前端校验机制.

    image-20230822152458908

    进入数据库了

    image-20230822152547676

    1. 后端校验-需求分析, 如果拿掉前端校验,会出现灰色框提示, 后台不真正入库数据

    image-20230822152647623

    思路分析

    1. 后台使用JSR303 数据校验,引入hibernate-validator.jar
    2. 前台使用ElementPlus 进行数据绑定,并显示错误信息

    代码实现

    1. 修改pom.xml 引入hibernate-validator jar 文件
    
    <dependency>
        <groupId>org.hibernategroupId>
        <artifactId>hibernate-validatorartifactId>
        <version>6.1.0.Finalversion>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    1. 修改Furn.java , 使用hibernate-validator
    /**
     * 如果Furn类名和表 furn名字不能对应,可以通过前面讲解的@TableName
     * 如果可以对应上,可以不写
     */
    @Data
    //@TableName("furn")
    public class Furn {
     
        //这里我们使用@TableId: 表主键标识
        //当我们在 private Integer id 上标识了@TableId
        //说明id 对应的就是表的id字段,而且是主键
        //type = IdType.AUTO 主键类型是自增长
        @TableId(type = IdType.AUTO)
        private Integer id;
        //根据自己的业务需求,来配置相应的注解
     
        //如果是对String进行非空校验,我们应该使用@NotEmpty
        @NotEmpty(message = "请输入家居名")
        private String name;
        @NotEmpty(message = "请输入厂商名")
        private String maker;
     
        @NotNull(message = "请输入数字")
        @Range(min = 0, message = "价格不能小于0")
        private BigDecimal price;
     
        @NotNull(message = "请输入数字")
        @Range(min = 0, message = "销量不能小于0")
        private Integer sales;
     
        @NotNull(message = "请输入数字")
        @Range(min = 0, message = "库存不能小于0")
        private Integer stock;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    1. 修改FurnController.java , 对save 方法进行完善
        @PostMapping("/save")
        public Result save(@Validated @RequestBody Furn furn, Errors errors) {
     
            //如果出现校验错误, sboot 底层会把错误信息,封装到errors
     
            //定义map ,准备把errors中的校验错误放入到map,如果有错误信息
            //就不真正添加,并且将错误信息通过map返回给客户端-客户端就可以取出显示
            HashMap<String, Object> map = new HashMap<>();
     
            List<FieldError> fieldErrors = errors.getFieldErrors();
            //遍历 将错误信息放入到map , 当然可能有,也可能没有错误
            for (FieldError fieldError : fieldErrors) {
                map.put(fieldError.getField(), fieldError.getDefaultMessage());
            }
            if (map.isEmpty()) { //说明没有校验错误,正常添加
                log.info("furn={}", furn);
                furnService.save(furn);
                return Result.success(); //返回成功信息
            } else {
                return Result.error("400", "后端校验失败~", map);
            }
     
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    1. 修改HomeView.vue , 显示服务器校验返回的提示信息
      ===在数据池,增加显示错误信息变量
    data() {
        return {
        //存放错误信息
        serverValidErrors: {},
    
    • 1
    • 2
    • 3
    • 4

    ====修改save()方法,显示错误提示

    save() {
        //增加处理修改逻辑
        if (this.form.id) {
            request.put("/api/update", this.form).then(res => {
                if (res.code === 200) {//如果code 为200
                    this.$message({ //弹出更新成功的消息框
                        type: "success",
                        message: "更新成功"
                    })
                } else {
                    this.$message({//弹出更新失败信息
                        type: "error",
                        message: res.msg
                    })
                }
                this.list() //刷新列表
                this.dialogVisible = false
            })
        } else {//添加
            //表单数据校验是否
            this.$refs['form'].validate((valid) => {
                if (valid) {
                    //=======说明======
                    //1. 将form 表单提交给/api/save 的接口
                    //2. /api/save 等价http://localhost:10001/save
                    //3. 如果成功,就进入then 方法
                    //4. res 就是返回的信息
                    //5. 查看Mysql 看看数据是否保存
                    request.post("/api/save", this.form).then(res => {
                        if (res.code === 200) {
                            this.dialogVisible = false
                            this.list()
                        } else if (res.code === 400) {
                            this.serverValidErrors.name = res.extend.errorMsg.name;
                            this.serverValidErrors.sales = res.extend.errorMsg.sales;
                            this.serverValidErrors.price = res.extend.errorMsg.price;
                            this.serverValidErrors.maker = res.extend.errorMsg.maker;
                            this.serverValidErrors.stock = res.extend.errorMsg.stock;
                        }
                    })
                } else {
                    this.$message({//弹出更新失败信息
                        type: "error",
                        message: "验证失败,不提交"
                    })
                    return false
                }
            })
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50

    完成测试

    启动项目后台服务springboot-furn
    启动项目前台springboot_vue
    浏览器输入: http://localhost:10000/

    测试页面效果

    ● 添加家居表单后端校验, 浏览器: http://localhost:10000/

    image-20230822153432500

    //表单数据校验是否通过
    this.$refs['form'].validate((valid) => {
        if (valid) { //测试前将valid 设置为true
            //=======说明======
            //1. 将form 表单提交给/api/save 的接口
            //2. /api/save 等价http://localhost:10000/save
            //3. 如果成功,就进入then 方法
            //4. res 就是返回的信息
            //5. 查看Mysql 看看数据是否保存
            request.post("/api/save", this.form).then(res => {
                if (res.code === "200") {
                    this.dialogVisible = false
                    this.list()
                } else if (res.code === "400") {
                    this.validMsg.name = res.data.name
                    this.validMsg.sales = res.data.sales
                    this.validMsg.price = res.data.price
                    this.validMsg.maker = res.data.maker
                    this.validMsg.stock = res.data.stock
            	}
        	})
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    测试完毕后, 记得把valid 改成正常逻辑.

    文章到这里就结束了,如果有什么疑问的地方请指出,诸大佬们一起来评论区一起讨论😁
    希望能和诸大佬们一起努力,今后我们一起观看感谢您的阅读🍻
    如果帮助到您不妨3连支持一下,创造不易您们的支持是我的动力🤞

  • 相关阅读:
    web3 dapp React项目引入 antd 对 balance 用户token信息组件进行样式改造
    中级深入--day16
    最新AI创作系统ChatGPT系统运营源码+支持GPT-4多模态模型
    openGauss学习笔记-96 openGauss 数据库管理-访问外部数据库-file_fdw
    PyTorch合集2
    Mybatis的关联关系配置一对一,一对多,多对多的映射关系
    【Python】12 GPflow安装
    springboot享瘦减肥中心管理系统
    pytorch训练错误记录
    rsync远程同步
  • 原文地址:https://blog.csdn.net/m0_73557631/article/details/132590594