SpringBoot參數(shù)校驗(yàn)與國(guó)際化使用教程
springboot 使用校驗(yàn)框架validation校驗(yàn)方法的入?yún)?/p>
SpringBoot的Web組件內(nèi)部集成了hibernate-validator,所以我們這里并不需要額外的為驗(yàn)證再導(dǎo)入其他的包。
1、bean 中添加標(biāo)簽標(biāo)簽需要加在屬性上,@NotEmpty標(biāo)簽String的參數(shù)不能為空
@Datapublic class DemoDto { @NotEmpty(message = '名稱不能為空') private String name; @Length(min = 5, max = 25, message = 'key的長(zhǎng)度為5-25') private String key; @Pattern(regexp = '[012]', message = '無效的狀態(tài)標(biāo)志') private String state;}2、Controller中開啟驗(yàn)證
在Controller 中 請(qǐng)求參數(shù)上添加@Validated 標(biāo)簽開啟驗(yàn)證
@RequestMapping('test') public String test(@Valid @RequestBody DemoDto dto){ System.out.println('test....................'); return 'test.........................'; }
測(cè)試返回結(jié)果
{ 'timestamp': '2020-01-14 13:30:03', 'status': 400, 'error': 'Bad Request', 'errors': [{ 'codes': ['Length.demoDto.key','Length.key','Length.java.lang.String','Length' ], 'arguments': [{ 'codes': ['demoDto.key','key' ], 'arguments': null, 'defaultMessage': 'key', 'code': 'key'},25,5 ], 'defaultMessage': 'key的長(zhǎng)度為5-25', 'objectName': 'demoDto', 'field': 'key', 'rejectedValue': '11', 'bindingFailure': false, 'code': 'Length'},{...},{...} ], 'message': 'Validation failed for object=’demoDto’. Error count: 3', 'path': '/test'}
返回的錯(cuò)誤信息比較亂,需要統(tǒng)一整理,這個(gè)時(shí)候可以使用全局異常處理的方法
3、異常處理,捕獲錯(cuò)誤信息當(dāng)驗(yàn)證不通過時(shí)會(huì)拋異常出來。在異常處理器中捕獲異常信息(因?yàn)轵?yàn)證不通過的項(xiàng)可能是多個(gè)所以統(tǒng)一捕獲處理),并拋給前端。(此處是前后端分離開發(fā))
@RequestMapping('test') public ResultBean test(@Valid @RequestBody DemoDto dto){ System.out.println('test....................'); return new ResultBean('test.........................'); }
這里統(tǒng)一返回一個(gè)自定義的ResultBean類型
@Slf4j@RestControllerAdvicepublic class GlobalExceptionHandler { @ExceptionHandler(value = MethodArgumentNotValidException.class) public ResultBean methodArgumentNotValid(HttpServletRequest req, MethodArgumentNotValidException ex) { ResultBean result = ResultBean.FAIL; List<ObjectError> errors =ex.getBindingResult().getAllErrors(); StringBuffer errorMsg=new StringBuffer(); errors.stream().forEach(x -> errorMsg.append(x.getDefaultMessage()).append(';')); log.error('---MethodArgumentNotValidException Handler--- ERROR: {}', errorMsg.toString()); result.setMsg(errorMsg.toString()); return result; }}
此時(shí)的返回結(jié)果為:
{ 'code': 500, 'msg': '無效的狀態(tài)標(biāo)志;key的長(zhǎng)度為5-25;名稱不能為空;', 'content': null}
二、分組校驗(yàn)有時(shí)候需要在不同的方法中對(duì)同一個(gè)bean中的參數(shù)進(jìn)行校驗(yàn)
1、在dto中添加groups@Datapublic class DemoDto { public interface Default { } public interface Update { } @NotEmpty(message = '名稱不能為空') private String name; @Length(min = 5, max = 25, message = 'key的長(zhǎng)度為5-25' ,groups = Default.class ) private String key; @Pattern(regexp = '[012]', message = '無效的狀態(tài)標(biāo)志',groups = {Default.class,Update.class} ) private String state;}
2、在controller中需要用到@Validated來校驗(yàn)
@RequestMapping('test2') public String test2(@Validated(value = DemoDto.Default.class) @RequestBody DemoDto dto){ System.out.println('test....................'); return 'test.........................'; } @RequestMapping('test4') public String test4(@Validated(value = {DemoDto.Default.class,DemoDto.Update.class}) @RequestBody DemoDto dto){ System.out.println('test....................'); return 'test.........................'; }三、國(guó)際化返回配置文件的信息1. 在Resource下添加properties文件
文件中添加需要打印的消息,如:
demo.key.null=demo的key不能為空start.ge.end = 開始日期{0}必須小于結(jié)束日期{1}!demo.key.length=demo的key長(zhǎng)度不正確2. 在application.yml中添加配置
spring: messages: encoding: UTF-8 basename: message/messages_zh3. 使用方法
在類中直接注入,即可使用
@Autowired private MessageSource messageSource; @RequestMapping('getMessageByKey') public ResultBean getMessageByKey(@Valid @RequestBody DemoDto dto){ String key = dto.getKey(); String [] param = {'2019-8-8', '2019-9-9'}; return new ResultBean(messageSource.getMessage(key, param, Locale.CHINA)); }
測(cè)試調(diào)用和返回結(jié)果,返回的數(shù)據(jù)和預(yù)期相符合
根據(jù)上面的修改
1、bean 中添加標(biāo)簽
標(biāo)簽需要加在屬性上,@NotEmpty標(biāo)簽String的參數(shù)不能為空
@Datapublic class DemoDto { @NotEmpty(message = '{demo.key.null}') @Length(min = 5, max = 25, message = '{demo.key.length}') private String key;}
2、添加上ValidationMessages文件
國(guó)際化配置文件必須放在classpath的根目錄下,即src/java/resources的根目錄下。
國(guó)際化配置文件必須以ValidationMessages開頭,比如ValidationMessages.properties 或者 ValidationMessages_en.properties。
在/resources的根目錄下添加上ValidationMessages.properties文件
demo.key.null=demo的key不能為空,這里是validationMessagedemo.key.length=demo的key長(zhǎng)度不正確
3、返回結(jié)果
{ 'code': 500, 'msg': 'demo的key不能為空,這里是validationMessage;', 'content': null}
自定義properties文件
SpringBoot 國(guó)際化驗(yàn)證 @Validated 的 message 國(guó)際化資源文件默認(rèn)必須放在 resources/ValidationMessages.properties 中。
現(xiàn)在我想把資源文件放到 resources/message/messages_zh.properties 中
若要自定義文件位置或名稱則需要重寫WebMvcConfigurerAdapter 的 getValidator 方法,但WebMvcConfigurerAdapter在springboot2中已經(jīng)廢棄了,可以改為使用WebMvcConfigurationSupport
在一的基礎(chǔ)上修改:
@Configurationpublic class ValidatorConfiguration extends WebMvcConfigurationSupport { @Autowired private MessageSource messageSource; @Override public Validator getValidator() { return validator(); } @Bean public Validator validator() { LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean(); validator.setValidationMessageSource(messageSource); return validator; }}
最后得到結(jié)果為:
{ 'code': 500, 'msg': 'demo的key不能為空ID:{0};', 'content': null}
參考文章:
spring boot國(guó)際化——MessageSource的使用
總結(jié)
到此這篇關(guān)于SpringBoot參數(shù)校驗(yàn)與國(guó)際化使用教程的文章就介紹到這了,更多相關(guān)SpringBoot參數(shù)校驗(yàn)與國(guó)際化使用內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. html中的form不提交(排除)某些input 原創(chuàng)2. ASP動(dòng)態(tài)網(wǎng)頁(yè)制作技術(shù)經(jīng)驗(yàn)分享3. vue使用moment如何將時(shí)間戳轉(zhuǎn)為標(biāo)準(zhǔn)日期時(shí)間格式4. jsp文件下載功能實(shí)現(xiàn)代碼5. 開發(fā)效率翻倍的Web API使用技巧6. ASP常用日期格式化函數(shù) FormatDate()7. js select支持手動(dòng)輸入功能實(shí)現(xiàn)代碼8. CSS3中Transition屬性詳解以及示例分享9. asp.net core項(xiàng)目授權(quán)流程詳解10. CSS3實(shí)現(xiàn)動(dòng)態(tài)翻牌效果 仿百度貼吧3D翻牌一次動(dòng)畫特效
