av一区二区在线观看_亚洲男人的天堂网站_日韩亚洲视频_在线成人免费_欧美日韩精品免费观看视频_久草视

您的位置:首頁(yè)技術(shù)文章
文章詳情頁(yè)

SpringBoot參數(shù)校驗(yàn)與國(guó)際化使用教程

瀏覽:87日期:2023-04-06 15:15:21
一、參數(shù)校驗(yàn)

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文件

SpringBoot參數(shù)校驗(yàn)與國(guó)際化使用教程

文件中添加需要打印的消息,如:

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ù)期相符合

SpringBoot參數(shù)校驗(yàn)與國(guó)際化使用教程

三、國(guó)際化參數(shù)校驗(yàn)

根據(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)!

標(biāo)簽: Spring
相關(guān)文章:
主站蜘蛛池模板: 久久久久国产 | 亚洲精品一区中文字幕乱码 | 亚洲欧洲一区二区 | 91操操操 | 亚洲国产成人精品女人 | 亚洲精品在线观看视频 | a级黄色毛片免费播放视频 国产精品视频在线观看 | 成人国产精品 | 波多野结衣中文字幕一区二区三区 | www.av在线| 99亚洲综合| 久久久久久免费看 | 亚洲啊v在线 | 国产成人精品免费 | 成人在线视 | 欧美一级片黄色 | 久久国产精品无码网站 | 国产亚洲网站 | 亚洲第一区久久 | 国产免费观看一区 | 国产在线观看一区二区三区 | 91精品国产综合久久小仙女图片 | 日韩福利在线观看 | 国产十日韩十欧美 | 国产免费视频在线 | 亚洲综合电影 | 蜜桃精品视频在线 | 久久午夜影院 | 国产成都精品91一区二区三 | 中国一级特黄毛片大片 | 国产精品一区二区免费 | 亚洲国产欧美在线 | 国产日韩欧美在线播放 | 亚洲午夜三级 | 午夜视频一区二区三区 | 国内精品久久精品 | 久久久久久亚洲精品 | 北条麻妃99精品青青久久 | 日本高清视频网站 | 亚洲福利在线视频 | 黄频免费|