SpringBoot參數(shù)校驗與國際化使用教程
一、參數(shù)校驗
springboot 使用校驗框架validation校驗方法的入?yún)?/p>
SpringBoot的Web組件內(nèi)部集成了hibernate-validator,所以我們這里并不需要額外的為驗證再導(dǎo)入其他的包。
1、bean 中添加標(biāo)簽
標(biāo)簽需要加在屬性上,@NotEmpty標(biāo)簽String的參數(shù)不能為空
@Data public class DemoDto { @NotEmpty(message = "名稱不能為空") private String name; @Length(min = 5, max = 25, message = "key的長度為5-25") private String key; @Pattern(regexp = "[012]", message = "無效的狀態(tài)標(biāo)志") private String state; }
2、Controller中開啟驗證
在Controller 中 請求參數(shù)上添加@Validated 標(biāo)簽開啟驗證
@RequestMapping("test") public String test(@Valid @RequestBody DemoDto dto){ System.out.println("test...................."); return "test........................."; }
測試返回結(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的長度為5-25",
"objectName": "demoDto",
"field": "key",
"rejectedValue": "11",
"bindingFailure": false,
"code": "Length"
},
{...},
{...}
],
"message": "Validation failed for object='demoDto'. Error count: 3",
"path": "/test"
}
返回的錯誤信息比較亂,需要統(tǒng)一整理,這個時候可以使用全局異常處理的方法
3、異常處理,捕獲錯誤信息
當(dāng)驗證不通過時會拋異常出來。在異常處理器中捕獲異常信息(因為驗證不通過的項可能是多個所以統(tǒng)一捕獲處理),并拋給前端。(此處是前后端分離開發(fā))
@RequestMapping("test") public ResultBean test(@Valid @RequestBody DemoDto dto){ System.out.println("test...................."); return new ResultBean("test........................."); }
這里統(tǒng)一返回一個自定義的ResultBean類型
@Slf4j @RestControllerAdvice public 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; } }
此時的返回結(jié)果為:
{
"code": 500,
"msg": "無效的狀態(tài)標(biāo)志;key的長度為5-25;名稱不能為空;",
"content": null
}
二、分組校驗
有時候需要在不同的方法中對同一個bean中的參數(shù)進(jìn)行校驗
1、在dto中添加groups
@Data public 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 = "無效的狀態(tài)標(biāo)志",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文件
文件中添加需要打印的消息,如:
demo.key.null=demo的key不能為空 start.ge.end = 開始日期{0}必須小于結(jié)束日期{1}! demo.key.length=demo的key長度不正確
2. 在application.yml中添加配置
spring: messages: encoding: UTF-8 basename: message/messages_zh
3. 使用方法
在類中直接注入,即可使用
@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)); }
測試調(diào)用和返回結(jié)果,返回的數(shù)據(jù)和預(yù)期相符合
三、國際化參數(shù)校驗
根據(jù)上面的修改
1、bean 中添加標(biāo)簽
標(biāo)簽需要加在屬性上,@NotEmpty標(biāo)簽String的參數(shù)不能為空
@Data public 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不能為空,這里是validationMessage demo.key.length=demo的key長度不正確
3、返回結(jié)果
{
"code": 500,
"msg": "demo的key不能為空,這里是validationMessage;",
"content": null
}
自定義properties文件
SpringBoot 國際化驗證 @Validated 的 message 國際化資源文件默認(rèn)必須放在 resources/ValidationMessages.properties 中。
現(xiàn)在我想把資源文件放到 resources/message/messages_zh.properties 中
若要自定義文件位置或名稱則需要重寫WebMvcConfigurerAdapter 的 getValidator 方法,但WebMvcConfigurerAdapter在springboot2中已經(jīng)廢棄了,可以改為使用WebMvcConfigurationSupport
在一的基礎(chǔ)上修改:
@Configuration public 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國際化——MessageSource的使用
總結(jié)
到此這篇關(guān)于SpringBoot參數(shù)校驗與國際化使用教程的文章就介紹到這了,更多相關(guān)SpringBoot參數(shù)校驗與國際化使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Springboot并發(fā)調(diào)優(yōu)之大事務(wù)和長連接
這篇文章主要介紹了Springboot并發(fā)調(diào)優(yōu)之大事務(wù)和長連接,重點分享長事務(wù)以及長連接導(dǎo)致的并發(fā)排查和優(yōu)化思路和示例,具有一定的參考價值,感興趣的可以了解一下2022-05-05Mybatis返回值(resultType&resultMap)的具體使用
返回值屬性有兩種設(shè)置,一種是resultType,一種是resultMap,本文主要介紹了Mybatis返回值(resultType&resultMap)的具體使用,具有一定的參考價值,感興趣的可以了解一下2023-08-08Jenkins自動化部署SpringBoot項目的實現(xiàn)
本文主要介紹了Jenkins自動化部署SpringBoot項目的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2023-01-01m1 Mac設(shè)置多jdk版本并動態(tài)切換的實現(xiàn)
本文主要介紹 Mac 下如何安裝 JDK 并且多版本如何切換,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-08-08Springboot升級到2.7.2結(jié)合nacos遇到的坑及解決
這篇文章主要介紹了Springboot升級到2.7.2結(jié)合nacos遇到的坑及解決,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-06-06