- 引入依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> <version>2.3.4.RELEASE</version> </dependency>
- 資料限制實體類代碼BrandEntity.java
package com.kenai.gulimall.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 zhaolijian * @email [email protected] * @date 2021-02-20 20:39:29 */ @Data @TableName("pms_brand") public class BrandEntity implements Serializable { private static final long serialVersionUID = 1L; /** * 品牌id */ @TableId private Long brandId; /** * 品牌名 */ @NotBlank(message = "品牌名不能為空") private String name; /** * 品牌logo位址 */ @NotBlank(message = "品牌logo位址不能為空") @URL(message = "logo必須是一個合法的url位址") private String logo; /** * 介紹 */ private String descript; /** * 顯示狀态[0-不顯示;1-顯示] */ private Integer showStatus; /** * 檢索首字母 */ @NotBlank(message = "檢索首字母不能為空") // ^: 比對輸入字元串的開始位置, $: 比對輸入字元串的結尾位置 @Pattern(regexp = "[a-zA-Z]", message = "檢索首字母必須是一個字母") private String firstLetter; /** * 排序 */ @NotNull(message = "排序字段不能為空") @Min(value = 0, message = "排序字段必須大于等于0") private Integer sort; }
- 資料校驗使用代碼
package com.kenai.gulimall.product.controller; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; 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 org.springframework.validation.BindingResult; import com.kenai.gulimall.product.entity.BrandEntity; import com.kenai.gulimall.product.service.BrandService; import com.kenai.common.utils.PageUtils; import com.kenai.common.utils.R; import javax.validation.Valid; /** * 品牌 * * @author zhaolijian * @email [email protected] * @date 2021-02-20 20:39:29 */ @RestController @RequestMapping("product/brand") public class BrandController { @Autowired private BrandService brandService; /** * 儲存 * @Valid注解的作用是讓BrandEntity滿足約定的規範,比如非空等 * BindingResult是規範校驗的傳回結果 */ @RequestMapping("/save") //@RequiresPermissions("product:brand:save") public R save(@Valid @RequestBody BrandEntity brand, BindingResult result){ if(result.hasErrors()){ Map<String, String> map = new HashMap<>(); result.getFieldErrors().forEach((item) -> { // 擷取錯誤的屬性名稱 String field = item.getField(); // 擷取錯誤提示 String message = item.getDefaultMessage(); map.put(field, message); }); return R.error(400, "送出的資料不合法").put("data", map); }else{ brandService.save(brand); return R.ok(); } } }
- 分組校驗
-
背景
有些字段在不同環境下的校驗規則不同
比如id在新增的時候必須為空,但是在修改的時候必須不為空
- 實體類(UpdateGroup.class、AddGroup.class為空接口)
package com.kenai.gulimall.product.entity; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import java.io.Serializable; import java.util.Date; import com.kenai.common.valid.AddGroup; import com.kenai.common.valid.UpdateGroup; import lombok.Data; import org.apache.ibatis.annotations.Update; import org.hibernate.validator.constraints.URL; import org.springframework.lang.Nullable; import javax.validation.constraints.*; /** * 品牌 * * @author zhaolijian * @email [email protected] * @date 2021-02-20 20:39:29 */ @Data @TableName("pms_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}) @TableId private Long brandId; /** * 品牌名 */ @NotBlank(message = "品牌名不能為空",groups = {UpdateGroup.class, AddGroup.class}) private String name; /** * 品牌logo位址 */ @NotBlank(message = "品牌logo位址不能為空",groups = {AddGroup.class}) @URL(message = "logo必須是一個合法的url位址",groups = {UpdateGroup.class, AddGroup.class}) private String logo; /** * 介紹 */ private String descript; /** * 顯示狀态[0-不顯示;1-顯示] */ private Integer showStatus; /** * 檢索首字母 */ @NotBlank(message = "檢索首字母不能為空",groups = {AddGroup.class}) // ^: 比對輸入字元串的開始位置, $: 比對輸入字元串的結尾位置 @Pattern(regexp = "[a-zA-Z]", message = "檢索首字母必須是一個字母",groups = {UpdateGroup.class, AddGroup.class}) private String firstLetter; /** * 排序 */ @NotNull(message = "排序字段不能為空",groups = {AddGroup.class}) @Min(value = 0, message = "排序字段必須大于等于0",groups = {UpdateGroup.class, AddGroup.class}) private Integer sort; }
- 邏輯處理類
/** * 使用統一異常處理,通過@RestControllerAdvice能自動擷取抛出的異常 * @Validated: 當使用JSR303分組校驗功能時,指定屬于哪個分組,同一個字段對于不同分組可能有不同的處理方式 * @param brand * @return */ @RequestMapping("/save") public R save(@Validated({AddGroup.class}) @RequestBody BrandEntity brand){ 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(); }
注: 在分組校驗的情況下(即邏輯處理類中的方法參數注解@Validated中有分組資訊,比如@Validated({UpdateGroup.class})), 沒有指定分組的實體類中校驗注解不生效.需要指定分組才能生效(即如@NotBlank(group={UpdateGroup.class})指定了分組才會生效).
要想使沒有指定分組的實體類中校驗注解生效,則邏輯處理類中的注解@Validated不能帶分組參數