最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Spring WebFlux實(shí)現(xiàn)參數(shù)校驗(yàn)的示例代碼

 更新時(shí)間:2021年08月08日 11:43:13   作者:lzyer  
請(qǐng)求參數(shù)校驗(yàn),在實(shí)際的應(yīng)用中很常見,網(wǎng)上的文章大部分提供的使用注解的方式做參數(shù)校驗(yàn)。本文主要介紹 Spring Webflux Function Endpoint 使用 Spring Validation 來校驗(yàn)請(qǐng)求的參數(shù)。感興趣的可以了解一下

請(qǐng)求參數(shù)校驗(yàn),在實(shí)際的應(yīng)用中很常見,網(wǎng)上的文章大部分提供的使用注解的方式做參數(shù)校驗(yàn)。本文主要介紹 Spring Webflux Function Endpoint 使用 Spring Validation 來校驗(yàn)請(qǐng)求的參數(shù)。使用上一篇文章的示例來演示。

使用步驟如下:

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;

@Component
public 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
@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());
    }
  }
    // .... 省略
}

請(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。

接下來,我們來看一下Validator 接口中的兩個(gè)方法 supportsvalidate

  • supports(Class) : 判斷當(dāng)前的校驗(yàn)器用指定的類上。
  • validate(Object, org.springframework.validation.Errors) : 校驗(yàn)給定的對(duì)象,如果出現(xiàn)錯(cuò)誤,就給Errors 注冊(cè) 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;
}

請(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)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • java中jdk的下載和安裝全過程

    java中jdk的下載和安裝全過程

    這篇文章主要給大家介紹了關(guān)于java中jdk的下載和安裝的相關(guān)資料,文中通過圖文介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-11-11
  • Intellij idea遠(yuǎn)程debug連接tomcat實(shí)現(xiàn)單步調(diào)試

    Intellij idea遠(yuǎn)程debug連接tomcat實(shí)現(xiàn)單步調(diào)試

    這篇文章主要介紹了Intellij idea遠(yuǎn)程debug連接tomcat實(shí)現(xiàn)單步調(diào)試,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2018-05-05
  • Spring boot 數(shù)據(jù)庫連接斷線重連問題

    Spring boot 數(shù)據(jù)庫連接斷線重連問題

    這篇文章主要介紹了Spring boot 數(shù)據(jù)庫連接斷線重連問題,需要的朋友可以參考下
    2017-06-06
  • org.springframework.beans.BeanInstantiationException異常解決

    org.springframework.beans.BeanInstantiationException異常解決

    本文主要介紹了org.springframework.beans.BeanInstantiationException異常解決,大多數(shù)情況下,這個(gè)異常是由于簡(jiǎn)單的配置錯(cuò)誤或者代碼問題導(dǎo)致的,下面就來具體解決一下
    2024-03-03
  • SpringBoot打成war包在tomcat或wildfly下運(yùn)行的方法

    SpringBoot打成war包在tomcat或wildfly下運(yùn)行的方法

    這篇文章主要介紹了SpringBoot打成war包在tomcat或wildfly下運(yùn)行的方法,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2019-11-11
  • ssm 使用token校驗(yàn)登錄的實(shí)現(xiàn)

    ssm 使用token校驗(yàn)登錄的實(shí)現(xiàn)

    這篇文章主要介紹了ssm 使用token校驗(yàn)登錄的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-04-04
  • SpringBoot整合RestTemplate用法的實(shí)現(xiàn)

    SpringBoot整合RestTemplate用法的實(shí)現(xiàn)

    本篇主要介紹了RestTemplate中的GET,POST,PUT,DELETE、文件上傳和文件下載6大常用的功能,具有一定的參考價(jià)值,感興趣的可以了解一下
    2023-08-08
  • Java ZooKeeper分布式鎖實(shí)現(xiàn)圖解

    Java ZooKeeper分布式鎖實(shí)現(xiàn)圖解

    ZooKeeper是一個(gè)分布式的,開放源碼的分布式應(yīng)用程序協(xié)調(diào)服務(wù),是Google的Chubby一個(gè)開源的實(shí)現(xiàn),是Hadoop和Hbase的重要組件。它是一個(gè)為分布式應(yīng)用提供一致性服務(wù)的軟件,提供的功能包括:配置維護(hù)、域名服務(wù)、分布式同步、組服務(wù)等
    2022-03-03
  • 詳解Java并發(fā)工具類之CountDownLatch和CyclicBarrier

    詳解Java并發(fā)工具類之CountDownLatch和CyclicBarrier

    在JDK的并發(fā)包中,有幾個(gè)非常有用的并發(fā)工具類,它們分別是:CountDownLatch、CyclicBarrier、Semaphore和Exchanger,本文主要來講講其中CountDownLatch和CyclicBarrier的使用,感興趣的可以了解一下
    2023-06-06
  • springboot時(shí)間格式化的五種方法總結(jié)(解決后端傳給前端的時(shí)間顯示不一致)

    springboot時(shí)間格式化的五種方法總結(jié)(解決后端傳給前端的時(shí)間顯示不一致)

    這篇文章主要給大家介紹了關(guān)于springboot時(shí)間格式化的五種方法,文中介紹的方法解決了后端傳給前端的時(shí)間顯示不一致,文中通過圖文以及代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2024-01-01

最新評(píng)論

苍梧县| 读书| 涟源市| 兰西县| 抚州市| 恩平市| 万安县| 白水县| 滁州市| 和田市| 南安市| 岳阳市| 景谷| 唐山市| 彰化市| 北辰区| 赣榆县| 华池县| 兴仁县| 息烽县| 西乌| 卢龙县| 隆昌县| 松原市| 甘谷县| 广德县| 马公市| 乌审旗| 新乡市| 毕节市| 大邑县| 扶沟县| 行唐县| 无锡市| 邮箱| 云阳县| 腾冲县| 玛多县| 喀喇| 宣城市| 犍为县|