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 = '名稱(chēng)不能為空') private String name; @Length(min = 5, max = 25, message = 'key的長(zhǎng)度為5-25') private String key; @Pattern(regexp = '[012]', message = '無(wú)效的狀態(tài)標(biāo)志') private String state;}2、Controller中開(kāi)啟驗(yàn)證
在Controller 中 請(qǐng)求參數(shù)上添加@Validated 標(biāo)簽開(kāi)啟驗(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)證不通過(guò)時(shí)會(huì)拋異常出來(lái)。在異常處理器中捕獲異常信息(因?yàn)轵?yàn)證不通過(guò)的項(xiàng)可能是多個(gè)所以統(tǒng)一捕獲處理),并拋給前端。(此處是前后端分離開(kāi)發(fā))
@RequestMapping('test') public ResultBean test(@Valid @RequestBody DemoDto dto){ System.out.println('test....................'); return new ResultBean('test.........................'); }
這里統(tǒng)一返回一個(gè)自定義的ResultBean類(lèi)型
@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': '無(wú)效的狀態(tài)標(biāo)志;key的長(zhǎng)度為5-25;名稱(chēng)不能為空;', '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 = '名稱(chēng)不能為空') private String name; @Length(min = 5, max = 25, message = 'key的長(zhǎng)度為5-25' ,groups = Default.class ) private String key; @Pattern(regexp = '[012]', message = '無(wú)效的狀態(tài)標(biāo)志',groups = {Default.class,Update.class} ) private String state;}
2、在controller中需要用到@Validated來(lái)校驗(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 = 開(kāi)始日期{0}必須小于結(jié)束日期{1}!demo.key.length=demo的key長(zhǎng)度不正確2. 在application.yml中添加配置
spring: messages: encoding: UTF-8 basename: message/messages_zh3. 使用方法
在類(lèi)中直接注入,即可使用
@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開(kāi)頭,比如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 中
若要自定義文件位置或名稱(chēng)則需要重寫(xiě)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. XHTML 1.0:標(biāo)記新的開(kāi)端2. 怎樣才能用js生成xmldom對(duì)象,并且在firefox中也實(shí)現(xiàn)xml數(shù)據(jù)島?3. python中的socket實(shí)現(xiàn)ftp客戶端和服務(wù)器收發(fā)文件及md5加密文件4. Java 生成帶Logo和文字的二維碼5. 基于javaweb+jsp實(shí)現(xiàn)企業(yè)財(cái)務(wù)記賬管理系統(tǒng)6. 低版本IE正常運(yùn)行HTML5+CSS3網(wǎng)站的3種解決方案7. xml中的空格之完全解說(shuō)8. Android自定義控件實(shí)現(xiàn)方向盤(pán)效果9. Javaweb工程運(yùn)行報(bào)錯(cuò)HTTP Status 404解決辦法10. asp讀取xml文件和記數(shù)
