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

012 表单校验

文章目录

    • BrandEntity.java
    • BrandController.java
    • 抽取
      • CubemallEnum.java
      • CubemallExceptionControllerAdvice.java
      • BrandController.java
      • BrandEntity.java
    • 分组
      • AddGroup.java
      • UpdateGroup.java
      • BrandController.java
      • BrandEntity.java
      • CubemallExceptionControllerAdvice.java
      • CubemallEnum.java

新增

127.0.0.1:8888/api/product/brand/save
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;-- ----------------------------
-- Table structure for tb_brand
-- ----------------------------
DROP TABLE IF EXISTS `tb_brand`;
CREATE TABLE `tb_brand`  (`id` int(0) NOT NULL AUTO_INCREMENT COMMENT '品牌id',`name` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '品牌名称',`image` varchar(1000) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT '' COMMENT '品牌图片地址',`letter` char(1) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT '' COMMENT '品牌的首字母',`seq` int(0) NULL DEFAULT NULL COMMENT '排序',PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 325431 CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci COMMENT = '品牌表' ROW_FORMAT = Dynamic;SET FOREIGN_KEY_CHECKS = 1;
        dataRule: {name: [{ required: true, message: '品牌名称不能为空', trigger: 'blur' }],image: [{ required: true, message: '品牌图片地址不能为空', trigger: 'blur' }],letter: [{validator: (rule, value, callback) => {if(value == ""){callback(new Error("首字母必须填写"))} else if(!/^[a-zA-Z]$/.test(value)){callback(new Error("首字母必须a-z或者A-Z之间"))} else {callback()}},trigger: 'blur'}],seq: [{validator: (rule, value, callback) => {if(value == ""){callback(new Error("排序字段必须填写"))} else if(!/^[0-9]+$/.test(value)){callback(new Error("排序必须是一个大于等于0的整数"))} else {callback()}},trigger: 'blur'}]}

BrandEntity.java

package com.xd.cubemall.product.entity;import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;import java.io.Serializable;
import java.util.Date;
import lombok.Data;
import org.hibernate.validator.constraints.URL;import javax.validation.constraints.*;/*** 品牌表* * @author xd* @email email@gmail.com* @date 2024-08-13 01:36:04*/
@Data
@TableName("tb_brand")
public class BrandEntity implements Serializable {private static final long serialVersionUID = 1L;/*** 品牌id*///@NotNull(message = "修改必须指定品牌id")@Null(message = "新增不能指定id")@TableIdprivate Integer id;/*** 品牌名称*/@NotBlank(message = "品牌名必须提交")private String name;/*** 品牌图片地址*/@URL(message = "logo必须是一个合法的url地址")private String image;/*** 品牌的首字母*/@NotEmpty()@Pattern(regexp = "^[a-zA-Z]$", message = "检索首字母必须是一个字母")private String letter;/*** 排序*/@NotNull@Min(value = 0, message = "排序必须大于等于0")private Integer seq;}

@NotNull、@NotEmpty、@NotBlank这三个注解都是用来进行空检查的,但是它们之间存在一些差异,适用于不同的场景。

@NotNull:用于任何对象,确保被注解的对象不为null。它可以用在任何类型的字段上,无论是基本数据类型还是对象。
@NotEmpty:用于集合类(如List、Set、Map等)或者数组,确保集合或数组不为空(即不为null且至少包含一个元素)。
@NotBlank:用于字符串,确保字符串不为空且不仅仅是空白字符(空格、tab、换行等)。
使用场景:

@NotNull:当你想要确保一个对象不为null时使用。
@NotEmpty:当你想要确保一个集合或数组不为空(即不为null且至少包含一个元素)时使用。
@NotBlank:当你想要确保一个字符串不为空且不仅仅是空白字符时使用。

关于@NotNull和@Null同时使用的情况,这实际上是一个特殊的应用场景,用于区分不同的操作(如新增和修改)。
@NotNull(message = “修改必须指定品牌id”):表示在进行修改操作时,必须指定品牌id,即id字段不能为null。
@Null(message = “新增不能指定id”):表示在进行新增操作时,不能指定品牌id,即id字段必须为null。

BrandController.java

package com.xd.cubemall.product.controller;import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;import com.xd.cubemall.common.utils.PageUtils;
import com.xd.cubemall.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;import com.xd.cubemall.product.entity.BrandEntity;
import com.xd.cubemall.product.service.BrandService;import javax.validation.Valid;/*** 品牌表** @author xuedong* @email email@gmail.com* @date 2024-08-13 07:57:20*/
@RestController
@RequestMapping("product/brand")
public class BrandController {@Autowiredprivate BrandService brandService;/*** 保存*/@RequestMapping("/save")//@RequiresPermissions("product:brand:save")public R save(@Valid @RequestBody BrandEntity brand, BindingResult result){if(result.hasErrors()){Map<String, String> map = new HashMap<>();//1.获取校验的错误结果result.getFieldErrors().forEach((fieldError) -> {//获取每个错误的属性的名字String field = fieldError.getField();//获取每个错误属性的提示String message = fieldError.getDefaultMessage();map.put(field, message);});return R.error(400, "提交的数据不合法").put("data",map);} else {brandService.save(brand);return R.ok();}}}

抽取

CubemallEnum.java

package com.xd.cubemall.common.exception;public enum CubemallEnum {UNKNOW_EXCEPTION(10000,"系统未知异常"),VAILD_EXCEPTION(10001,"参数格式校验失败");private int code;private String msg;CubemallEnum(int code, String msg){this.code = code;this.msg = msg;}public int getCode() {return code;}public String getMsg() {return msg;}
}

CubemallExceptionControllerAdvice.java

package com.xd.cubemall.product.exception;import com.xd.cubemall.common.exception.CubemallEnum;
import com.xd.cubemall.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;import java.util.HashMap;
import java.util.Map;/*** Controller层 统一异常处理*/
@Slf4j
@RestControllerAdvice(basePackages = "com.xd.cubemall.product.controller")
public class CubemallExceptionControllerAdvice {//如果能够精确匹配到该异常就会执行这个方法,后续执行下面的方法@ExceptionHandler(value = MethodArgumentNotValidException.class)public R handleVaildException(MethodArgumentNotValidException e){log.error("数据校验出现问题{},异常类型{}",e.getMessage(),e.getCause());//1.获取校验的错误结果BindingResult result = e.getBindingResult();Map<String, String> map = new HashMap<>();result.getFieldErrors().forEach((fieldError) -> {//获取每个错误的属性的名字String field = fieldError.getField();//获取每个错误属性的提示String message = fieldError.getDefaultMessage();map.put(field, message);});return R.error(CubemallEnum.VAILD_EXCEPTION.getCode(), CubemallEnum.VAILD_EXCEPTION.getMsg()).put("data",map);}@ExceptionHandler(value = Throwable.class)public R handleVaildException(Throwable throwable){log.error("错误",throwable);return R.error(CubemallEnum.UNKNOW_EXCEPTION.getCode(), CubemallEnum.UNKNOW_EXCEPTION.getMsg()).put("data","未知异常");}}

BrandController.java

package com.xd.cubemall.product.controller;import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;import com.xd.cubemall.common.utils.PageUtils;
import com.xd.cubemall.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;import com.xd.cubemall.product.entity.BrandEntity;
import com.xd.cubemall.product.service.BrandService;import javax.validation.Valid;/*** 品牌表** @author xd* @email email@gmail.com* @date 2024-08-13 07:57:20*/
@RestController
@RequestMapping("product/brand")
public class BrandController {@Autowiredprivate BrandService brandService;@RequestMapping("/save")//@RequiresPermissions("product:brand:save")public R save(@Valid @RequestBody BrandEntity brand){//        if(result.hasErrors()){
//            Map<String, String> map = new HashMap<>();
//            //1.获取校验的错误结果
//            result.getFieldErrors().forEach((fieldError) -> {
//                //获取每个错误的属性的名字
//                String field = fieldError.getField();
//                //获取每个错误属性的提示
//                String message = fieldError.getDefaultMessage();
//
//                map.put(field, message);
//            });
//            return R.error(400, "提交的数据不合法").put("data",map);
//        } else {
//            brandService.save(brand);
//            return R.ok();
//        }brandService.save(brand);return R.ok();}
}

BrandEntity.java

package com.xd.cubemall.product.entity;import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;import java.io.Serializable;
import java.util.Date;
import lombok.Data;
import org.hibernate.validator.constraints.URL;import javax.validation.constraints.*;/*** 品牌表* * @author xd* @email email@gmail.com* @date 2024-08-13 01:36:04*/
@Data
@TableName("tb_brand")
public class BrandEntity implements Serializable {private static final long serialVersionUID = 1L;/*** 品牌id*///@NotNull(message = "修改必须指定品牌id")@Null(message = "新增不能指定id")@TableIdprivate Integer id;/*** 品牌名称*/@NotBlank(message = "品牌名必须提交")private String name;/*** 品牌图片地址*/@URL(message = "logo必须是一个合法的url地址")private String image;/*** 品牌的首字母*/@NotEmpty()@Pattern(regexp = "^[a-zA-Z]$", message = "检索首字母必须是一个字母")private String letter;/*** 排序*/@NotNull@Min(value = 0, message = "排序必须大于等于0")private Integer seq;}

分组

AddGroup.java

package com.xd.cubemall.common.valid;public interface AddGroup {
}

UpdateGroup.java

package com.xd.cubemall.common.valid;public interface UpdateGroup {
}

BrandController.java

package com.xd.cubemall.product.controller;import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;import com.xd.cubemall.common.utils.PageUtils;
import com.xd.cubemall.common.utils.R;
import com.xd.cubemall.common.valid.AddGroup;
import com.xd.cubemall.common.valid.UpdateGroup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;import com.xd.cubemall.product.entity.BrandEntity;
import com.xd.cubemall.product.service.BrandService;import javax.validation.Valid;/*** 品牌表** @author xd* @email email@gmail.com* @date 2024-08-13 07:57:20*/
@RestController
@RequestMapping("product/brand")
public class BrandController {@Autowiredprivate BrandService brandService;/*** 保存*/@RequestMapping("/save")//@RequiresPermissions("product:brand:save")public R save(@Validated({AddGroup.class}) @RequestBody BrandEntity brand) {//        if(result.hasErrors()){
//            Map<String, String> map = new HashMap<>();
//            //1.获取校验的错误结果
//            result.getFieldErrors().forEach((fieldError) -> {
//                //获取每个错误的属性的名字
//                String field = fieldError.getField();
//                //获取每个错误属性的提示
//                String message = fieldError.getDefaultMessage();
//
//                map.put(field, message);
//            });
//            return R.error(400, "提交的数据不合法").put("data",map);
//        } else {
//            brandService.save(brand);
//            return R.ok();
//        }brandService.save(brand);return R.ok();}/*** 修改*/@RequestMapping("/update")//@RequiresPermissions("product:brand:update")public R update(@Validated({UpdateGroup.class}) @RequestBody BrandEntity brand){brandService.updateById(brand);return R.ok();}}

BrandEntity.java

package com.xd.cubemall.product.entity;import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;import java.io.Serializable;
import java.util.Date;import com.xd.cubemall.common.valid.AddGroup;
import com.xd.cubemall.common.valid.UpdateGroup;
import lombok.Data;
import org.hibernate.validator.constraints.URL;import javax.validation.constraints.*;/*** 品牌表* * @author xd* @email email@gmail.com* @date 2024-08-13 01:36:04*/
@Data
@TableName("tb_brand")
public class BrandEntity implements Serializable {private static final long serialVersionUID = 1L;/*** 品牌id*/@NotNull(message = "修改必须指定品牌id", groups = {UpdateGroup.class})@Null(message = "新增不能指定id", groups = {AddGroup.class})@TableIdprivate Integer id;/*** 品牌名称*/@NotBlank(message = "品牌名必须提交", groups = {AddGroup.class, UpdateGroup.class})private String name;/*** 品牌图片地址*/@NotBlank(groups = {AddGroup.class})@URL(message = "logo必须是一个合法的url地址", groups = {AddGroup.class, UpdateGroup.class})private String image;/*** 品牌的首字母*/@NotEmpty(groups = {AddGroup.class})@Pattern(regexp = "^[a-zA-Z]$", message = "检索首字母必须是一个字母", groups = {AddGroup.class, UpdateGroup.class})private String letter;/*** 排序*/@NotNull(groups = {AddGroup.class})@Min(value = 0, message = "排序必须大于等于0", groups = {AddGroup.class, UpdateGroup.class})private Integer seq;}

CubemallExceptionControllerAdvice.java

package com.xd.cubemall.product.exception;import com.xd.cubemall.common.exception.CubemallEnum;
import com.xd.cubemall.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;import java.util.HashMap;
import java.util.Map;/*** Controller层 统一异常处理*/
@Slf4j
@RestControllerAdvice(basePackages = "com.xd.cubemall.product.controller")
public class CubemallExceptionControllerAdvice {//如果能够精确匹配到该异常就会执行这个方法,后续执行下面的方法@ExceptionHandler(value = MethodArgumentNotValidException.class)public R handleVaildException(MethodArgumentNotValidException e){log.error("数据校验出现问题{},异常类型{}",e.getMessage(),e.getCause());//1.获取校验的错误结果BindingResult result = e.getBindingResult();Map<String, String> map = new HashMap<>();result.getFieldErrors().forEach((fieldError) -> {//获取每个错误的属性的名字String field = fieldError.getField();//获取每个错误属性的提示String message = fieldError.getDefaultMessage();map.put(field, message);});return R.error(CubemallEnum.VAILD_EXCEPTION.getCode(), CubemallEnum.VAILD_EXCEPTION.getMsg()).put("data",map);}@ExceptionHandler(value = Throwable.class)public R handleVaildException(Throwable throwable){log.error("错误",throwable);return R.error(CubemallEnum.UNKNOW_EXCEPTION.getCode(), CubemallEnum.UNKNOW_EXCEPTION.getMsg()).put("data","未知异常");}}

CubemallEnum.java

package com.xd.cubemall.common.exception;public enum CubemallEnum {UNKNOW_EXCEPTION(10000,"系统未知异常"),VAILD_EXCEPTION(10001,"参数格式校验失败");private int code;private String msg;CubemallEnum(int code, String msg){this.code = code;this.msg = msg;}public int getCode() {return code;}public String getMsg() {return msg;}
}

http://www.mrgr.cn/news/9670.html

相关文章:

  • QTCreator学习
  • 一款人性化的终端用户界面工具
  • Redis笔记
  • 中间件(22) : nginx通过http接口获取代理目标地址(win)|nginx自定义负载均衡算法
  • 在vue2中,使用计算属性,具体代码如下:
  • Stable Diffusion 3「精神续作」FLUX.1 源码深度前瞻解读
  • K8S - Java微服务配置 - 使用ConfigMap配置redis
  • Excel VBA 编程学习指南,1.2 VBA与Excel的关系
  • 前端宝典十九:高频算法之动态规划
  • (第三十三天)
  • 判断变量是否为数组
  • 案例-登录认证
  • RFID光触发标签在物流仓储的深度应用与技术优势解读
  • flutter GestureDetector 的 behavior属性
  • 设计模式 2 抽象工厂模式
  • Android strings.xml中定义字符串显示空格
  • C++设计模式3:工厂模式
  • Python和MATLAB梯度下降导图
  • 【数据结构-前缀异或和】力扣1177. 构建回文串检测
  • Edge-TTS:微软推出的,免费、开源、支持多种中文语音语色的AI工具[工具版]