您的位置:首頁技術文章
文章詳情頁

SpringBoot參數校驗與國際化使用教程

瀏覽:35日期:2023-04-06 15:15:21
一、參數校驗

springboot 使用校驗框架validation校驗方法的入參

SpringBoot的Web組件內部集成了hibernate-validator,所以我們這里并不需要額外的為驗證再導入其他的包。

1、bean 中添加標簽

標簽需要加在屬性上,@NotEmpty標簽String的參數不能為空

@Datapublic class DemoDto { @NotEmpty(message = '名稱不能為空') private String name; @Length(min = 5, max = 25, message = 'key的長度為5-25') private String key; @Pattern(regexp = '[012]', message = '無效的狀態標志') private String state;}2、Controller中開啟驗證

在Controller 中 請求參數上添加@Validated 標簽開啟驗證

@RequestMapping('test') public String test(@Valid @RequestBody DemoDto dto){ System.out.println('test....................'); return 'test.........................'; }

測試返回結果

{ '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的長度為5-25', 'objectName': 'demoDto', 'field': 'key', 'rejectedValue': '11', 'bindingFailure': false, 'code': 'Length'},{...},{...} ], 'message': 'Validation failed for object=’demoDto’. Error count: 3', 'path': '/test'}

返回的錯誤信息比較亂,需要統一整理,這個時候可以使用全局異常處理的方法

3、異常處理,捕獲錯誤信息

當驗證不通過時會拋異常出來。在異常處理器中捕獲異常信息(因為驗證不通過的項可能是多個所以統一捕獲處理),并拋給前端。(此處是前后端分離開發)

@RequestMapping('test') public ResultBean test(@Valid @RequestBody DemoDto dto){ System.out.println('test....................'); return new ResultBean('test.........................'); }

這里統一返回一個自定義的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; }}

此時的返回結果為:

{ 'code': 500, 'msg': '無效的狀態標志;key的長度為5-25;名稱不能為空;', 'content': null}

二、分組校驗

有時候需要在不同的方法中對同一個bean中的參數進行校驗

1、在dto中添加groups

@Datapublic class DemoDto { public interface Default { } public interface Update { } @NotEmpty(message = '名稱不能為空') private String name; @Length(min = 5, max = 25, message = 'key的長度為5-25' ,groups = Default.class ) private String key; @Pattern(regexp = '[012]', message = '無效的狀態標志',groups = {Default.class,Update.class} ) private String state;}

2、在controller中需要用到@Validated來校驗

@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.........................'; }三、國際化返回配置文件的信息1. 在Resource下添加properties文件

SpringBoot參數校驗與國際化使用教程

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

demo.key.null=demo的key不能為空start.ge.end = 開始日期{0}必須小于結束日期{1}!demo.key.length=demo的key長度不正確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)); }

測試調用和返回結果,返回的數據和預期相符合

SpringBoot參數校驗與國際化使用教程

三、國際化參數校驗

根據上面的修改

1、bean 中添加標簽

標簽需要加在屬性上,@NotEmpty標簽String的參數不能為空

@Datapublic class DemoDto { @NotEmpty(message = '{demo.key.null}') @Length(min = 5, max = 25, message = '{demo.key.length}') private String key;}

2、添加上ValidationMessages文件

國際化配置文件必須放在classpath的根目錄下,即src/java/resources的根目錄下。

國際化配置文件必須以ValidationMessages開頭,比如ValidationMessages.properties 或者 ValidationMessages_en.properties。

在/resources的根目錄下添加上ValidationMessages.properties文件

demo.key.null=demo的key不能為空,這里是validationMessagedemo.key.length=demo的key長度不正確

3、返回結果

{ 'code': 500, 'msg': 'demo的key不能為空,這里是validationMessage;', 'content': null}

自定義properties文件

SpringBoot 國際化驗證 @Validated 的 message 國際化資源文件默認必須放在 resources/ValidationMessages.properties 中。

現在我想把資源文件放到 resources/message/messages_zh.properties 中

若要自定義文件位置或名稱則需要重寫WebMvcConfigurerAdapter 的 getValidator 方法,但WebMvcConfigurerAdapter在springboot2中已經廢棄了,可以改為使用WebMvcConfigurationSupport

在一的基礎上修改:

@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; }}

最后得到結果為:

{ 'code': 500, 'msg': 'demo的key不能為空ID:{0};', 'content': null}

參考文章:

spring boot國際化——MessageSource的使用

總結

到此這篇關于SpringBoot參數校驗與國際化使用教程的文章就介紹到這了,更多相關SpringBoot參數校驗與國際化使用內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!

標簽: Spring
相關文章:
国产综合久久一区二区三区