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

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

SpringBoot接口参数校验

發(fā)布時間:2024/10/6 javascript 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 SpringBoot接口参数校验 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

一、JSR303校驗

1.使用校驗注解

<!--Valid--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-validation</artifactId><version>2.3.2.RELEASE</version></dependency><!--自定義注解--><dependency><groupId>javax.validation</groupId><artifactId>validation-api</artifactId><version>2.0.1.Final</version></dependency>

(1)@NotNull
The annotated element must not be null. Accepts any type.
注解元素禁止為null,能夠接收任何類型
(2)@NotEmpty
the annotated element must not be null nor empty.
該注解修飾的字段不能為null或""
Supported types are:
支持以下幾種類型
CharSequence (length of character sequence is evaluated)
字符序列(字符序列長度的計算)
Collection (collection size is evaluated)
集合長度的計算
Map (map size is evaluated)
map長度的計算
Array (array length is evaluated)
數(shù)組長度的計算

(3)@NotBlank

The annotated element must not be null and must contain at least one non-whitespace character. Accepts CharSequence.
該注解不能為null,并且至少包含一個非空白字符。接收字符序列。

package com.atguigu.gulimall.product.entity;import com.atguigu.common.valid.AddGroup; import com.atguigu.common.valid.ListValue; import com.atguigu.common.valid.UpdateGroup; import com.atguigu.common.valid.UpdateStatusGroup; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; import org.hibernate.validator.constraints.URL;import javax.validation.constraints.*; import java.io.Serializable;/*** 品牌* * @author steven* @email steven@gmail.com* @date 2022-01-08 16:31:09*/ @Data @TableName("pms_brand") public class BrandEntity implements Serializable {private static final long serialVersionUID = 1L;/*** 品牌id*/@Null(message = "新增品牌ID必須為空",groups = {AddGroup.class})@NotNull(message = "修改是品牌ID不能為空",groups = {UpdateGroup.class})@TableIdprivate Long brandId;/*** 品牌名*/@NotBlank(message = "品牌名不能為空",groups = {AddGroup.class,UpdateGroup.class})private String name;/*** 品牌logo地址*/@NotEmpty(message = "商品logo地址不能為空",groups = {AddGroup.class})//,groups = {AddGroup.class, UpdateGroup.class}@URL(message = "logo必須是一個合法的url地址",groups = {AddGroup.class,UpdateGroup.class})private String logo;/*** 介紹*/private String descript;/*** 顯示狀態(tài)[0-不顯示;1-顯示]*/@NotNull(message = "狀態(tài)不能為空",groups = {AddGroup.class,UpdateStatusGroup.class})@ListValue(vals = {0,1},groups = {AddGroup.class, UpdateStatusGroup.class})private Integer showStatus;/*** 檢索首字母*/@NotBlank(message = "檢索首字母不能為空",groups = {AddGroup.class})@Pattern(regexp = "^[a-zA-Z]$",message = "檢索首字母必須是一個字母",groups = {AddGroup.class,UpdateGroup.class})private String firstLetter;/*** 排序*/@NotNull(message = "排序字段不能為空",groups = {AddGroup.class})@Min(value = 0,message = "排序必須大于等于0",groups = {AddGroup.class,UpdateGroup.class})private Integer sort; }

2:在請求方法種,使用校驗注解@Validated,開啟校驗

/*** 修改*/@RequestMapping("/update")public R update(@Validated @RequestBody BrandEntity brand){brandService.updateById(brand);return R.ok();}

這些錯誤消息定義在“hibernate-validator”的“\org\hibernate\validator\ValidationMessages_zh_CN.properties”文件中。在該文件中定義了很多的錯誤規(guī)則:

javax.validation.constraints.AssertFalse.message = 只能為false javax.validation.constraints.AssertTrue.message = 只能為true javax.validation.constraints.DecimalMax.message = 必須小于或等于{value} javax.validation.constraints.DecimalMin.message = 必須大于或等于{value} javax.validation.constraints.Digits.message = 數(shù)字的值超出了允許范圍(只允許在{integer}位整數(shù)和{fraction}位小數(shù)范圍內(nèi)) javax.validation.constraints.Email.message = 不是一個合法的電子郵件地址 javax.validation.constraints.Future.message = 需要是一個將來的時間 javax.validation.constraints.FutureOrPresent.message = 需要是一個將來或現(xiàn)在的時間 javax.validation.constraints.Max.message = 最大不能超過{value} javax.validation.constraints.Min.message = 最小不能小于{value} javax.validation.constraints.Negative.message = 必須是負數(shù) javax.validation.constraints.NegativeOrZero.message = 必須是負數(shù)或零 javax.validation.constraints.NotBlank.message = 不能為空 javax.validation.constraints.NotEmpty.message = 不能為空 javax.validation.constraints.NotNull.message = 不能為null javax.validation.constraints.Null.message = 必須為null javax.validation.constraints.Past.message = 需要是一個過去的時間 javax.validation.constraints.PastOrPresent.message = 需要是一個過去或現(xiàn)在的時間 javax.validation.constraints.Pattern.message = 需要匹配正則表達式"{regexp}" javax.validation.constraints.Positive.message = 必須是正數(shù) javax.validation.constraints.PositiveOrZero.message = 必須是正數(shù)或零 javax.validation.constraints.Size.message = 個數(shù)必須在{min}和{max}之間org.hibernate.validator.constraints.CreditCardNumber.message = 不合法的信用卡號碼 org.hibernate.validator.constraints.Currency.message = 不合法的貨幣 (必須是{value}其中之一) org.hibernate.validator.constraints.EAN.message = 不合法的{type}條形碼 org.hibernate.validator.constraints.Email.message = 不是一個合法的電子郵件地址 org.hibernate.validator.constraints.Length.message = 長度需要在{min}和{max}之間 org.hibernate.validator.constraints.CodePointLength.message = 長度需要在{min}和{max}之間 org.hibernate.validator.constraints.LuhnCheck.message = ${validatedValue}的校驗碼不合法, Luhn模10校驗和不匹配 org.hibernate.validator.constraints.Mod10Check.message = ${validatedValue}的校驗碼不合法, 模10校驗和不匹配 org.hibernate.validator.constraints.Mod11Check.message = ${validatedValue}的校驗碼不合法, 模11校驗和不匹配 org.hibernate.validator.constraints.ModCheck.message = ${validatedValue}的校驗碼不合法, ${modType}校驗和不匹配 org.hibernate.validator.constraints.NotBlank.message = 不能為空 org.hibernate.validator.constraints.NotEmpty.message = 不能為空 org.hibernate.validator.constraints.ParametersScriptAssert.message = 執(zhí)行腳本表達式"{script}"沒有返回期望結(jié)果 org.hibernate.validator.constraints.Range.message = 需要在{min}和{max}之間 org.hibernate.validator.constraints.SafeHtml.message = 可能有不安全的HTML內(nèi)容 org.hibernate.validator.constraints.ScriptAssert.message = 執(zhí)行腳本表達式"{script}"沒有返回期望結(jié)果 org.hibernate.validator.constraints.URL.message = 需要是一個合法的URLorg.hibernate.validator.constraints.time.DurationMax.message = 必須小于${inclusive == true ? '或等于' : ''}${days == 0 ? '' : days += '天'}${hours == 0 ? '' : hours += '小時'}${minutes == 0 ? '' : minutes += '分鐘'}${seconds == 0 ? '' : seconds += '秒'}${millis == 0 ? '' : millis += '毫秒'}${nanos == 0 ? '' : nanos += '納秒'} org.hibernate.validator.constraints.time.DurationMin.message = 必須大于${inclusive == true ? '或等于' : ''}${days == 0 ? '' : days += '天'}${hours == 0 ? '' : hours += '小時'}${minutes == 0 ? '' : minutes += '分鐘'}${seconds == 0 ? '' : seconds += '秒'}${millis == 0 ? '' : millis += '毫秒'}${nanos == 0 ? '' : nanos += '納秒'}

3:給校驗的Bean后,緊跟一個BindResult,就可以獲取到校驗的結(jié)果。拿到校驗的結(jié)果,就可以自定義的封裝。

public R save(@Validated @RequestBody BrandEntity brand, BindingResult bindingResult){Map<String,String> map = new HashMap<>();if(bindingResult.hasErrors()){bindingResult.getFieldErrors().stream().forEach(item->{String field = item.getField();String defaultMessage = item.getDefaultMessage();map.put(field, defaultMessage);});return R.error(400,"參數(shù)錯誤").put("data", map);}else{brandService.save(brand);return R.ok();}}

4.統(tǒng)一異常處理

可以使用SpringMvc所提供的@ControllerAdvice,通過“basePackages”能夠說明處理哪些路徑下的異常。

package com.bigdata.gulimall.product.exception;import com.bigdata.common.utils.R; import lombok.extern.slf4j.Slf4j; import org.springframework.validation.BindingResult; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestControllerAdvice;import java.util.HashMap; import java.util.Map;/*** 集中處理所有異常*/ @Slf4j @RestControllerAdvice(basePackages = "com.bigdata.gulimall.product.controller") public class GulimallExceptionAdvice {@ExceptionHandler(value = Exception.class)public R handleValidException(MethodArgumentNotValidException exception){Map<String,String> map=new HashMap<>();BindingResult bindingResult = exception.getBindingResult();bindingResult.getFieldErrors().forEach(fieldError -> {String message = fieldError.getDefaultMessage();String field = fieldError.getField();map.put(field,message);});log.error("數(shù)據(jù)校驗出現(xiàn)問題{},異常類型{}",exception.getMessage(),exception.getClass());return R.error(400,"數(shù)據(jù)校驗出現(xiàn)問題").put("data",map);} }

二、 分組校驗功能(完成多場景的復(fù)雜校驗)

1、給校驗注解,標(biāo)注上groups,指定什么情況下才需要進行校驗

如:指定在更新和添加的時候,都需要進行校驗

@NotEmpty@NotBlank(message = "品牌名必須非空",groups = {UpdateGroup.class,AddGroup.class})private String name;

在這種情況下,沒有指定分組的校驗注解,默認是不起作用的。想要起作用就必須要加groups。

2、業(yè)務(wù)方法參數(shù)上使用@Validated注解

@Validated的value方法:
Specify one or more validation groups to apply to the validation step kicked off by this annotation.
指定一個或多個驗證組以應(yīng)用于此注釋啟動的驗證步驟。
JSR-303 defines validation groups as custom annotations which an application declares for the sole purpose of using
them as type-safe group arguments, as implemented in SpringValidatorAdapter.
JSR-303 將驗證組定義為自定義注釋,應(yīng)用程序聲明的唯一目的是將它們用作類型安全組參數(shù),如 SpringValidatorAdapter 中實現(xiàn)的那樣。
Other SmartValidator implementations may support class arguments in other ways as well.
其他SmartValidator 實現(xiàn)也可以以其他方式支持類參數(shù)。

默認情況下,在分組校驗情況下,沒有指定指定分組的校驗注解,將不會生效,它只會在不分組的情況下生效。

三、自定義校驗功能

1.編寫一個自定義的校驗注解

@Documented @Constraint(validatedBy = { ListValueConstraintValidator.class}) @Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE }) @Retention(RUNTIME) public @interface ListValue {String message() default "{com.bigdata.common.valid.ListValue.message}";Class<?>[] groups() default { };Class<? extends Payload>[] payload() default { };int[] value() default {}; }

2.編寫一個自定義的校驗器

public class ListValueConstraintValidator implements ConstraintValidator<ListValue,Integer> {private Set<Integer> set=new HashSet<>();@Overridepublic void initialize(ListValue constraintAnnotation) {int[] value = constraintAnnotation.value();for (int i : value) {set.add(i);}}@Overridepublic boolean isValid(Integer value, ConstraintValidatorContext context) {return set.contains(value);} }

指向自定義校驗類 @Constraint(validatedBy = { ListValueConstraintValidator.class})

編寫自定義提示文件放到resource目錄下 ValidationMessages.properties

com.atguigu.common.valid.ListValue.message=必須提交指定的值

總結(jié)

以上是生活随笔為你收集整理的SpringBoot接口参数校验的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。