Validation 校验参数-API 、⾃定义、⼿动校验
Validation 校验参数-API 、⾃定义、⼿动校验
Validation 校验参数-API 、⾃定义、⼿动校验
依赖
约束性注解
注解 作⽤
@Null 被注释的元素_值必须为 null
@NotNull 被注释的元素_值必须不为 null
@Pattern(regex=) 被注释的元素字符串_必须符合指定的正则表达式
@Size(max=, min=) 集合元素数量必须在min和max范围内
@AsrtTrue 被注释的元素必须为 true
@AsrtFal 被注释的元素必须为 fal
@Min(value) 被注释的元素必须是⼀个数字,其值必须⼤于等于指定的最⼩值
@Max(value) 被注释的元素必须是⼀个数字,其值必须⼩于等于指定的最⼤值
@Range(min,max) 数字必须在min和max范围内
@DecimalMin(value) 被注释的元素必须是⼀个数字,其值必须⼤于等于指定的最⼩值
@DecimalMax(value) 被注释的元素必须是⼀个数字,其值必须⼩于等于指定的最⼤值
@Digits (integer, fraction) 被注释的元素必须是⼀个数字,其值必须在可接受的范围内
@Past 被注释的元素必须是⼀个过去的⽇期
@Future 被注释的元素必须是⼀个将来的⽇期
@Email 字符串必须是Email地址
@SafeHtml 字符串必须是安全的html
@URL 字符串必须是合法的URL
@CreditCardNumber(ignoreNonDigitCharacters=) 字符串必须是信⽤卡号,按照美国的标准验证
@Size(max,min) 限制字符长度必须在min到max之间
@Validated 与@Valid 的简单对⽐说明
@Valid注解与@Validated注解功能⼤部分类似;两者的不同主要在于:@Valid属于javax下的,⽽@Validated属于spring下;@Valid⽀持嵌套校验、⽽@Validated不⽀持,@Validated⽀持分组,⽽@Valid不⽀持
Demo <dependency > <groupId >org.springframework.boot </groupId > <artifactId >spring-boot-starter-validation </artifactId > </dependency >
1
2
3
4
校验
⾃动校验
Controller添加@Valid或者@Validated都可以
⼿动校验import Data ;import ToString ;import Min ;import NotBlank ;import Pattern ;import Size ;@Data @ToString public class DevEquipment { @NotBlank(message = "aa") @Min(value = 6, message = "aa") private String a ; @NotBlank(message = "bb") @Size(min = 6,message = "bb") private String b ; @NotBlank(message = "cc") @Pattern(regexp = "1|2|3", message = "cc") private String c ; @Email(message ="⾮法邮件地址") private String email ;}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31@RestController @RequestMapping("/")public class UrController { @RequestMapping("testValidation") public String testValidation (@Valid @RequestBody DevEquipment devEquipment ) { return "success"; }}
1
2
3
4
5
6
7
8
9
10
全局异常拦截
⾃定义异常⽇期格式 private String validateDevEquipment (DevEquipment devEquipment ) { //先进⾏参数校验 StringBuilder returnSb = new StringBuilder (); Set <ConstraintViolation <DevEquipment >> validateResult = Validation .buildDefaultValidatorFactory ().getValidator ().validate (devEquipment , Default if (validateResult .size () > 0) { Iterator <ConstraintViolation <DevEquipment >> it = validateResult .iterator (); while (it .hasNext ()) { ConstraintViolation <DevEquipment > cv = it .next (); returnSb .append (cv .getPropertyPath () + ":" + cv .getMessage ()).append (";"); } } return returnSb .toString (); }
1
2
3
4
5
6
7
8
9
10
11
12
13/** * 参数合法性校验异常 * @param exception * @return */@ResponBody @ExceptionHandler(MethodArgumentNotValidException .class )public String validationBodyException (MethodArgumentNotValidException exception ){ StringBuffer buffer = new StringBuffer (); BindingResult result = exception .getBindingResult (); if (result .hasErrors ()) { List <ObjectError > errors = result .getAllErrors (); errors .forEach (p ->{ FieldError fieldError = (FieldError ) p ; log .error ("Data check failure : object{"+fieldError .getObjectName ()+"},field{"+fieldError .getField ()+ "},errorMessage{"+fieldError .getDefaultMessage ()+"}"); buffer .append (fieldError .getDefaultMessage ()).append (","); }); } BaRespon respon = new BaRespon (BusinessCodeEnum .INVALID_PARAM ); respon .tRespMsg (buffer .toString ().substring (0, buffer .toString ().length ()-1)); return JSONObject .toJSONString (respon );}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29import StringUtils ;
import *;import Documented ;import Retention ;import Target ;import SimpleDateFormat ;import static ElementType .*;import static RetentionPolicy .RUNTIME ;/**1
2
3
4
5
6
7
8
9
10
11
12
查库的/** * @author 67546 */@Documented @Constraint(validatedBy = {DateValid .DateValidator .class })@Target({METHOD , FIELD , ANNOTATION_TYPE , CONSTRUCTOR , PARAMETER })@Retention(RUNTIME )@ReportAsSingleViolation public @interface DateValid { String message () default "⽇期格式不正确"; Class <?>[] groups () default {}; Class <? extends Payload >[] payload () default {}; /** * 有效的⽇期格式 */ String [] format () default {}; @Target({METHOD , FIELD , ANNOTATION_TYPE , CONSTRUCTOR , PARAMETER }) @Retention(RUNTIME ) @Documented @interface List { DateValid [] value (); } class DateValidator implements ConstraintValidator <DateValid , String > { private String [] formats ; @Override public void initialize (DateValid constraintAnnotation ) { formats = constra
intAnnotation .format (); } @Override public boolean isValid (String value , ConstraintValidatorContext context ) { if (StringUtils .isBlank (value )){ return true ; } if (formats .length == 0) { return true ; } for (String string : formats ) { try { SimpleDateFormat formatter = new SimpleDateFormat (string ); formatter .par (value ); } catch (Exception e ) { return fal ; } } return true ; } }}12131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
import SpringUtil ;import UUnitMapper ;import StringUtils ;import *;import Documented ;import Retention ;import Target ;import static ElementType .*;import static RetentionPolicy .RUNTIME ;/** * @author Ybb * @Classname UUnitCodeVScope * @Description TODO * @Date 2022/2/8 15:49 * @Created by Ybb */@Documented @Constraint(validatedBy = {UUnitCodeScope .UUnitCodeValidator .class })@Target({TYPE , ANNOTATION_TYPE , FIELD })@Retention(RUNTIME )@ReportAsSingleViolation public @interface UUnitCodeScope { String message () default "{xx}"; Class <?>[] groups () default {}; Class <? extends Payload >[] payload () default {}; class UUnitCodeValidator implements ConstraintValidator <UUnitCodeScope , String > { private UUnitMapper uUnitMapper ; @Override p
ublic void initialize (UUnitCodeScope constraintAnnotation ) { this .uUnitMapper = SpringUtil .getBean ("uUnitMapper"); } @Override public boolean isValid (String value , ConstraintValidatorContext context ) { if (StringUtils .isBlank (value )){ return fal ; } int count = uUnitMapper .queryUUnitCode (value ); if (count > 0) { return true ; } return fal ; } }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455