日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

SpringBoot - 优雅的实现【参数校验】高级进阶

發布時間:2025/3/21 javascript 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 SpringBoot - 优雅的实现【参数校验】高级进阶 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

文章目錄

  • Pre
  • 概述
  • 參數校驗三部曲
    • Step1 搞依賴
    • Step2 搞參數校驗的實體類
      • 常用的校驗注解
    • Step3 開始驗證
    • 存在的問題
    • 使用 統一格式 + 全局異常Handler 優化
  • 源碼


Pre

SpringBoot - 優雅的實現【參數校驗】高級進階

SpringBoot - 優雅的實現【自定義參數校驗】高級進階

SpringBoot - 優雅的實現【參數分組校驗】高級進階

SpringBoot - 使用Assert校驗讓業務代碼更簡潔


概述

日常開發中,對入參進行參數校驗是必不可少的一個環節。 而使用最多的就是Validator框架 。

Validator校驗框架遵循了JSR-303 【Java Specification Requests】驗證規范 。

這里我們探討下,在boot項目中如何優雅的集成參數校驗框架


參數校驗三部曲

Step1 搞依賴

boot 2.3 以后版本的pom信息如下

<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-validation</artifactId></dependency></dependencies>
  • spring boot-2.3之前的版本只需要引入 spring-boot-starter-web 即可 ,已經包含了

  • spring boot-2.3及以后的版本,校驗包是一個單獨的starter,需要同時引入spring-boot-starter-validation


Step2 搞參數校驗的實體類

package com.artisan.vo;import lombok.Data; import org.hibernate.validator.constraints.Length;import javax.validation.constraints.Email; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotEmpty;/*** @author 小工匠* @version 1.0 * @mark: show me the code , change the world*/@Data public class Artisan {private String id;@NotBlank(message = "名字為必填項")private String name;@Length(min = 8, max = 12, message = "password長度必須位于8到12之間")private String password;@Email(message = "請填寫正確的郵箱地址")private String email;private String sex;@NotEmpty(message = "Code不能為空")private String code; }

常用的校驗注解

注解功能
@AssertFalse可以為null,如果不為null的話必須為false
@AssertTrue可以為null,如果不為null的話必須為true
@DecimalMax設置不能超過最大值
@DecimalMin設置不能超過最小值
@Digits設置必須是數字且數字整數的位數和小數的位數必須在指定范圍內
@Future日期必須在當前日期的未來
@Past日期必須在當前日期的過去
@Max最大不得超過此最大值
@Min最大不得小于此最小值
@NotNull不能為null,可以是空
@Null必須為null
@Pattern必須滿足指定的正則表達式
@Size集合、數組、map等的size()值必須在指定范圍內
@Email必須是email格式
@Length長度必須在指定范圍內
@NotBlank字符串不能為null,字符串trim()后也不能等于“”
@NotEmpty不能為null,集合、數組、map等size()不能為0;字符串trim()后可以等于“”
@Range值必須在指定范圍內
@URL必須是一個URL


Step3 開始驗證

注意看注釋

package com.artisan.controller;import com.artisan.vo.Artisan; import lombok.extern.slf4j.Slf4j; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*;import javax.validation.constraints.Email;/*** @author 小工匠* @version 1.0* @mark: show me the code , change the world*/@RestController @Slf4j @Validated @RequestMapping("/valid") public class ArtisanController {/*** 使用@RequestBody注解,用于接受前端發送的json數據** @param artisan* @return*/@PostMapping("/testJson")public String testJson(@Validated @RequestBody Artisan artisan) {log.info("InComing Param {}", artisan);return "testJson valid success";}/*** 模擬表單提交** @param artisan* @return*/@PostMapping(value = "/testForm")public String testForm(@Validated Artisan artisan) {log.info("InComing Param is {}", artisan);return "testForm valid success";}/*** 模擬單參數提交** @param email* @return*/@PostMapping(value = "/testParma")public String testParma(@Email String email) {log.info("InComing Param is {}", email);return "testParma valid success";}}
  • testJson使用 @RequestBody注解,用于接受前端發送的json數據

  • testForm模擬表單提交

  • testParma模擬單參數提交

    當使用單參數校驗時需要在Controller上加上@Validated注解,否則不生效

【測試第一個接收JSON的接口 】

可以看到拋出的異常為: org.springframework.web.bind.MethodArgumentNotValidException


【測試第二個接收表單的接口 】


可以看到拋出的異常為: org.springframework.validation.BindException


【測試第三個接收單參數的接口 】

可以看到拋出的異常為:javax.validation.ConstraintViolationException


存在的問題

且不說好不好看, 不管怎么樣,現在是通過Validation框架實現了校驗。 當然了,我們的追求肯定不是這樣的,Validator校驗框架返回的錯誤提示太臃腫了 ,格式啥的都不一樣,很難搞哦, 怎么給前臺返回????


使用 統一格式 + 全局異常Handler 優化

增加統一返回 和 全局異常Handler,單獨攔截參數校驗的三個異常:javax.validation.ConstraintViolationException,org.springframework.validation.BindException,org.springframework.web.bind.MethodArgumentNotValidException

/*** @param e* @return*/@ExceptionHandler(value = {BindException.class, ValidationException.class, MethodArgumentNotValidException.class})public ResponseEntity<ResponseData<String>> handleValidatedException(Exception e) {ResponseData<String> resp = null;if (e instanceof MethodArgumentNotValidException) {// BeanValidation exceptionMethodArgumentNotValidException ex = (MethodArgumentNotValidException) e;resp = ResponseData.fail(HttpStatus.BAD_REQUEST.value(),ex.getBindingResult().getAllErrors().stream().map(ObjectError::getDefaultMessage).collect(Collectors.joining("; ")));} else if (e instanceof ConstraintViolationException) {// BeanValidation GET simple paramConstraintViolationException ex = (ConstraintViolationException) e;resp = ResponseData.fail(HttpStatus.BAD_REQUEST.value(),ex.getConstraintViolations().stream().map(ConstraintViolation::getMessage).collect(Collectors.joining("; ")));} else if (e instanceof BindException) {// BeanValidation GET object paramBindException ex = (BindException) e;resp = ResponseData.fail(HttpStatus.BAD_REQUEST.value(),ex.getAllErrors().stream().map(ObjectError::getDefaultMessage).collect(Collectors.joining("; ")));}log.error("參數校驗異常:{}", resp.getMessage());return new ResponseEntity<>(resp, HttpStatus.BAD_REQUEST);}

重新測試


源碼

https://github.com/yangshangwei/boot2

總結

以上是生活随笔為你收集整理的SpringBoot - 优雅的实现【参数校验】高级进阶的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。