Spring Boot 通過注解實(shí)現(xiàn)數(shù)據(jù)校驗(yàn)的方法
一、依賴
<!--https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-validation --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> <version>2.3.3.RELEASE</version> </dependency>
二、實(shí)體類
@TableField('username') @NotBlank(message = '{user.name.notBlank}') private String username; @NotBlank(message = '{user.password.notBlank}') @TableField('password') private String password; @NotBlank(message = '{user.email.notBlank}') @Email(message = '{user.email.pattern}') @TableField('email') private String email;
三、配置
查看LocalValidationFactoryBean類的源碼,發(fā)現(xiàn)Spring Boot默認(rèn)的ValidationMessagesSource校驗(yàn)出錯(cuò)時(shí)的提示文件是在resources文件夾下文件ValidationMessages.properties
ValidationMessages.properties
user.name.notBlank=用戶名不能為空user.password.notBlank=密碼不能為空user.email.notBlank=郵箱不能為空user.email.pattern=郵箱格式不正確
四、Controller
/** * 添加用戶 * * @param user 用戶對(duì)象 * @return */ @PostMapping('/insert') public ResultVO<Object> insert(@Validated @RequestBody User user, BindingResult bindingResult) { if (bindingResult.hasErrors()) { List<ObjectError> allErrors = bindingResult.getAllErrors(); return ResultVOUtil.fail(allErrors.stream().map(ObjectError::getDefaultMessage).collect(Collectors.toList())); } userService.insert(user.doBuild()); return ResultVOUtil.success(); }
五、效果
到此這篇關(guān)于Spring Boot 通過注解實(shí)現(xiàn)數(shù)據(jù)校驗(yàn)的文章就介紹到這了,更多相關(guān)Spring Boot 數(shù)據(jù)校驗(yàn)內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. python 如何在 Matplotlib 中繪制垂直線2. bootstrap select2 動(dòng)態(tài)從后臺(tái)Ajax動(dòng)態(tài)獲取數(shù)據(jù)的代碼3. ASP常用日期格式化函數(shù) FormatDate()4. python 制作網(wǎng)站小說下載器5. html中的form不提交(排除)某些input 原創(chuàng)6. CSS3中Transition屬性詳解以及示例分享7. js select支持手動(dòng)輸入功能實(shí)現(xiàn)代碼8. python中@contextmanager實(shí)例用法9. 開發(fā)效率翻倍的Web API使用技巧10. vue使用moment如何將時(shí)間戳轉(zhuǎn)為標(biāo)準(zhǔn)日期時(shí)間格式
