Spring WebFlux實(shí)現(xiàn)參數(shù)校驗(yàn)的示例代碼
請(qǐng)求參數(shù)校驗(yàn),在實(shí)際的應(yīng)用中很常見(jiàn),網(wǎng)上的文章大部分提供的使用注解的方式做參數(shù)校驗(yàn)。本文主要介紹 Spring Webflux Function Endpoint 使用 Spring Validation 來(lái)校驗(yàn)請(qǐng)求的參數(shù)。使用上一篇文章的示例來(lái)演示。
使用步驟如下:1.創(chuàng)建校驗(yàn)器 Validator
2.運(yùn)用校驗(yàn)器
3.拋出異常,返回 http status 400 錯(cuò)誤
PersonValidator.java
package com.example.springbootdemo.webflux.restful;import org.springframework.stereotype.Component;import org.springframework.validation.Errors;import org.springframework.validation.ValidationUtils;import org.springframework.validation.Validator;@Componentpublic class PersonValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return Person.class.isAssignableFrom(clazz); } // 校驗(yàn)參數(shù)的方法 @Override public void validate(Object o, Errors errors) { ValidationUtils.rejectIfEmpty(errors, 'name', 'name.required'); ValidationUtils.rejectIfEmpty(errors, 'age', 'age.required'); Person p = (Person) o; if (p.getAge() != null && p.getAge() < 0) { errors.rejectValue('age', 'negative.value'); } else if (p.getAge() != null && p.getAge() > 200) { errors.rejectValue('age', 'too.old'); } }}
校驗(yàn)器在 savePerson 方法中的使用
@Slf4j@Componentpublic class PersonHandler { @Autowired private PersonRepository repository; @Autowired private PersonValidator validator; public Mono<ServerResponse> savePerson(ServerRequest request) { Mono<Person> personMono = request.bodyToMono(Person.class).doOnNext(this::validate); return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).body(this.repository.savePerson(personMono), Void.class); } public void validate(Person person) { Errors errors = new BeanPropertyBindingResult(person, Person.class.getName()); validator.validate(person, errors); if (errors.hasErrors()) {// 拋出 http status 400 異常 throw new ServerWebInputException(errors.toString()); } } // .... 省略}
請(qǐng)求效果:

官方校驗(yàn)參數(shù)示例的地址 https://docs.spring.io/spring-framework/docs/current/reference/html/web-reactive.html
使用 Spring 官方文檔提供的示例不會(huì)拋出 http code 400 錯(cuò)誤,返回的是http code 為 200。
接下來(lái),我們來(lái)看一下Validator 接口中的兩個(gè)方法 supports 和 validate
supports(Class) : 判斷當(dāng)前的校驗(yàn)器用指定的類(lèi)上。 validate(Object, org.springframework.validation.Errors) : 校驗(yàn)給定的對(duì)象,如果出現(xiàn)錯(cuò)誤,就給Errors 注冊(cè) Error 信息。另外,Spring 還提供了非常好用的 ValidationUtils 的工具類(lèi),提供了靜態(tài)的方法
rejectIfEmpty rejectIfEmptyOrWhitespace全局異常的使用
@Configuration@Slf4jpublic class GlobalErrorConfig { private ObjectMapper objectMapper = new ObjectMapper(); @Bean @Order(-2) public WebExceptionHandler exceptionHandler() { return (ServerWebExchange serverWebExchange, Throwable t) -> { DataBuffer dataBuffer = serverWebExchange.getResponse().bufferFactory().allocateBuffer(); Result result = new Result(); if (t instanceof ServerWebInputException) {ServerWebInputException exception = (ServerWebInputException) t;result.setCode(exception.getStatus().value());result.setMessage(exception.getReason()); } else {result.setCode(HttpStatus.INTERNAL_SERVER_ERROR.value());result.setMessage(HttpStatus.INTERNAL_SERVER_ERROR.toString()); } try {dataBuffer.write(objectMapper.writeValueAsBytes(result)); } catch (JsonProcessingException e) {log.error(NestedExceptionUtils.buildMessage('write error', e)); } ServerHttpResponse response = serverWebExchange.getResponse(); response.setRawStatusCode(result.getCode()); return response.writeWith(Mono.just(dataBuffer)); }; }}
Result.java
import lombok.Getter;import lombok.Setter;@Getter@Setterpublic class Result { private Integer code; private String message;}
請(qǐng)求效果:

至此,Webflux 的Function Endpoint 的參數(shù)校驗(yàn)的使用結(jié)束了。
參考:
WebFlux Handler Validation
Spring Validator
到此這篇關(guān)于Spring WebFlux實(shí)現(xiàn)參數(shù)校驗(yàn)的示例代碼的文章就介紹到這了,更多相關(guān)Spring WebFlux 參數(shù)校驗(yàn)內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. 理解PHP5中static和const關(guān)鍵字2. Android table布局開(kāi)發(fā)實(shí)現(xiàn)簡(jiǎn)單計(jì)算器3. python 代碼實(shí)現(xiàn)k-means聚類(lèi)分析的思路(不使用現(xiàn)成聚類(lèi)庫(kù))4. IntelliJ IDEA安裝插件的方法步驟5. Java如何基于反射機(jī)制獲取不同的類(lèi)6. php模擬實(shí)現(xiàn)斗地主發(fā)牌7. Vue封裝一個(gè)TodoList的案例與瀏覽器本地緩存的應(yīng)用實(shí)現(xiàn)8. Android 在 res/layout 文件夾 下創(chuàng)建一個(gè) 子文件夾實(shí)例9. PHP安全-命令注入10. Vuex localStorage的具體使用

網(wǎng)公網(wǎng)安備