網站首頁 編程語言 正文
一:SpringBoot的數據校驗(@Validated注解)、關于validation無法導入的問題解決
在springboot中,@Validated可對后臺接收model進行數據校驗,不符合則拋出異常。
導入依賴:
<!-- validation組件 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
如果在你導入validation包的時候,出現爆紅,檢查springboot的版本,本人親測validation在springboot的2.3.4.RELEASE版本可以導入,不會出現問題其他問題
使用樣例:
1.在實體類中定義注解
@Data
@EqualsAndHashCode(callSuper = false)
@TableName("sys_role")
@ApiModel(value="Role對象", description="")
public class Role implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.AUTO)
private Long id;
@NotNull(message = "角色名稱不能為空")
private String name;
@NotNull(message = "角色編碼不能為空")
private String code;
@ApiModelProperty(value = "備注")
private String remark;
private LocalDateTime created;
private LocalDateTime updated;
private Integer statu;
@TableField(exist = false)
private List<Long> menuIds = new ArrayList<>();
}
2.在controller層的方法形參前進行聲明
@PostMapping("/save")
public Result save(@Validated @RequestBody Role role){
role.setCreated(LocalDateTime.now());
role.setStatu(Const.STATIC_OFF);
roleService.save(role);
return Result.succ(role);
}
常用注解:
@AssertFalse 校驗false
@AssertTrue 校驗true
@DecimalMax(value=,inclusive=) 小于等于value,inclusive=true,是小于等于
@DecimalMin(value=,inclusive=) 與上類似
@Max(value=) 小于等于value
@Min(value=) 大于等于value
@NotNull 檢查Null
@Past 檢查日期
@Pattern(regex=,flag=) 正則
@Size(min=, max=) 字符串,集合,map限制大小
@Validate 對po實體類進行校驗(若modelA中存在modelB,可使用@Validate聲明modelB進行校驗,具體校驗規則在modelB進行聲明)
二:自定義校驗注解
自定義 @IsMobile注解演示:由于下面的代碼是本人在項目中粘貼出的,會有一些包沒有的現象,請大家見諒。
第一步:新建一個IsMobile類
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.ElementType.TYPE_USE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE })
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = { IsMobileValidator.class})
public @interface IsMobile {
boolean required() default true;
String message() default "手機號碼格式錯誤";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
}
第二步:@Constraint(validatedBy = { IsMobileValidator.class})
定義校驗類
public class IsMobileValidator implements ConstraintValidator<IsMobile,String> {
private boolean required = false;
@Override
public void initialize(IsMobile constraintAnnotation) {
required = constraintAnnotation.required();
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
if(required){
return ValidatorUtil.isMobile(value);
}else{
if(StringUtils.isEmpty(value)){
return true;
}else {
return ValidatorUtil.isMobile(value);
}
}
}
}
上面使用的ValidatorUtil類
/**
* 手機號碼校驗
*/
public class ValidatorUtil {
private static final Pattern mobile_pattern = Pattern.compile("[1]([3-9])[0-9]{9}$");
public static boolean isMobile(String mobile){
if(StringUtils.isEmpty(mobile)){
return false;
}
Matcher matcher = mobile_pattern.matcher(mobile);
return matcher.matches();
}
}
原文鏈接:https://blog.csdn.net/qq_51269815/article/details/124919509
相關推薦
- 2023-11-21 Ubuntu/Linux解壓文件、壓縮文件(.tar .tgz .tar.gz .tar.Z .ta
- 2022-07-27 Go?error的使用方式詳解_Golang
- 2023-06-03 C/C++中#define的妙用分享_C 語言
- 2022-12-22 一文學會c語言結構體的定義和使用方法_C 語言
- 2023-04-02 GoLang調用鏈可視化go-callvis使用介紹_Golang
- 2023-04-12 如何徹底解決python?NameError:name?'__file__'?is?not?defi
- 2022-01-31 微信小程序獲取二維碼中URL中帶的參數
- 2022-05-01 pytorch中的torch.nn.Conv2d()函數圖文詳解_python
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支