Spring WebFlux實現(xiàn)參數(shù)校驗的示例代碼
請求參數(shù)校驗,在實際的應(yīng)用中很常見,網(wǎng)上的文章大部分提供的使用注解的方式做參數(shù)校驗。本文主要介紹 Spring Webflux Function Endpoint 使用 Spring Validation 來校驗請求的參數(shù)。使用上一篇文章的示例來演示。
使用步驟如下:
1.創(chuàng)建校驗器 Validator
2.運用校驗器
3.拋出異常,返回 http status 400 錯誤
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; @Component public class PersonValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return Person.class.isAssignableFrom(clazz); } // 校驗參數(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"); } } }
校驗器在 savePerson
方法中的使用
@Slf4j @Component public 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()); } } // .... 省略 }
請求效果:
官方校驗參數(shù)示例的地址 https://docs.spring.io/spring-framework/docs/current/reference/html/web-reactive.html
使用 Spring 官方文檔提供的示例不會拋出 http code 400 錯誤,返回的是http code 為 200。
接下來,我們來看一下Validator
接口中的兩個方法 supports
和 validate
supports(Class)
: 判斷當前的校驗器用指定的類上。validate(Object, org.springframework.validation.Errors)
: 校驗給定的對象,如果出現(xiàn)錯誤,就給Errors
注冊Error
信息。
另外,Spring 還提供了非常好用的 ValidationUtils
的工具類,提供了靜態(tài)的方法
- rejectIfEmpty
- rejectIfEmptyOrWhitespace
全局異常的使用
@Configuration @Slf4j public 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 @Setter public class Result { private Integer code; private String message; }
請求效果:
至此,Webflux 的Function Endpoint 的參數(shù)校驗的使用結(jié)束了。
參考:
到此這篇關(guān)于Spring WebFlux實現(xiàn)參數(shù)校驗的示例代碼的文章就介紹到這了,更多相關(guān)Spring WebFlux 參數(shù)校驗內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Spring中的@RestControllerAdvice注解使用解析
這篇文章主要介紹了Spring中的@RestControllerAdvice注解使用解析,@RestControllerAdvice?是?Spring?框架中一個用于統(tǒng)一處理控制器異常和返回結(jié)果的注解,它可以被用來定義全局異常處理程序和全局響應(yīng)結(jié)果處理程序,需要的朋友可以參考下2024-01-01通過AOP環(huán)繞通知如何實現(xiàn)事務(wù)控制
這篇文章主要介紹了通過AOP環(huán)繞通知如何實現(xiàn)事務(wù)控制的操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-09-09Mybatis輸入輸出映射及動態(tài)SQL Review
這篇文章主要介紹了Mybatis輸入輸出映射及動態(tài)SQL Review,需要的朋友可以參考下2017-02-02使用Spring AOP監(jiān)控指定方法執(zhí)行時間的代碼詳解
這篇文章主要介紹了使用Spring AOP監(jiān)控指定方法執(zhí)行時間,文中通過代碼示例給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下2024-08-08Java正則表達式判斷是否包含數(shù)字、字母、特殊字符及中文的多種方法
這篇文章主要給大家介紹了關(guān)于Java正則表達式判斷是否包含數(shù)字、字母、特殊字符及中文的多種方法,Java正則表達式在字符串處理和模式匹配中扮演著重要角色,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下2023-08-08maven <repositories>標簽和<pluginRepositories>標簽的使用
這篇文章主要介紹了maven <repositories>標簽和<pluginRepositories>標簽的使用,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-07-07