好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

java自定义注解验证手机格式的实现示例

1、@Valid与@Validated的区别

1.1 基本区别

@Valid:Hibernate validation校验机制

@Validated:Spring Validator校验机制,这个也是最常用的

@Validation只是对@Valid进行了二次封装,在使用上并没有太大区别,但在分组、注解位置、嵌套验证等功能上有所不同

1.2 作用范围

@Validated:用在类型、方法和方法参数上。但不能用于成员属性(field)
@Valid:可以用在方法、构造函数、方法参数和成员属性(field)上

1.3 分组校验

@Validated:提供分组功能,可以在参数验证时,根据不同的分组采用不同的验证机制,注解中必须提供groups属性,该属性就是做分组的必要参数
@Valid:没有分组功能

2、未使用分组校验的示例

注解:

?

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

/**

  * 手机号验证正则

  */

@Target ({ElementType.FIELD,ElementType.METHOD})

@Retention (RetentionPolicy.RUNTIME)

@Documented

@Constraint (validatedBy = {PhoneValidator. class }) // 指定约束处理器,也就是手机号格式验证是哪个类来做校验

public @interface Phone {

 

   String pattern() default "^(?:(?:\\+|00)86)?1\\d{10}$" ;

 

   String message() default "手机号格式非法" ;

 

   Class<?>[] groups() default { }; // groups用来指定分组,可以让校验采取不同的机制,当前默认未指定任何分组机制,默认每次都要进行校验

 

   Class<? extends Payload>[] payload() default { };

  

   // 默认分组

   interface Default{

 

   }

 

   // 分组A

   interface A{

 

   }

}

格式校验处理器:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

/**

  * 校验处理器:做手机号码格式验证的核心类

  */

public class PhoneValidator implements ConstraintValidator<Phone, String> {

 

   // 注解对象

   private Phone phone;

 

   // 初始化【Phone】对象

   @Override

   public void initialize(Phone constraintAnnotation) {

     phone = constraintAnnotation;

   }

 

   @Override

   public boolean isValid(String value, ConstraintValidatorContext context) {

     // 获取【Phone】对象的手机格式验证表达式

     String pattern = phone.pattern();

     Pattern compile = Pattern测试数据pile(pattern);

     Matcher matcher = compile.matcher(value);

     return matcher.matches();

   }

作用类:

?

1

2

3

4

5

6

7

8

@Data

@EqualsAndHashCode (callSuper = false )

@Accessors (chain = true )

public class Person implements Serializable {

  

   @Phone

   private String phone;

}

注意:只有在spring或者springboot项目中才能使用,直接调用方法不会有任何效果,使用注解进行对象的属性格式校验时,必须配合@Validated一起使用(不一起使用,格式校验注解将会无效),正确操作如下:

?

1

2

3

4

5

6

7

8

9

10

11

12

@RestController

@RequestMapping ( "/admin/" )

public class PersonController {

 

   @Autowired

   private PersonService personService;

 

   @PostMapping ( "/query" )

   public Person query( @RequestBody @Validated Person params) {

     return JsonResult.success(personService.queryByPhone(params));

   }

}

以上示例未使用分组功能,因此每次都会校验。

3、分组校验的示例

使用分组校验示示例时,先要看看@Validated注解,因为分组校验就是配合该注解一起使用的,通过阅读注释就能理解到value属性就是用来指定分组的:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

@Target ({ElementType.TYPE, ElementType.METHOD, ElementType.PARAMETER})

@Retention (RetentionPolicy.RUNTIME)

@Documented

public @interface Validated {

 

  /**

  * Specify one or more validation groups to apply to the validation step

  * kicked off by this annotation.

  * <p>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

  * {@link org.springframework.validation.beanvalidation.SpringValidatorAdapter}.

  * <p>Other {@link org.springframework.validation.SmartValidator} implementations may

  * support class arguments in other ways as well.

  */

  Class<?>[] value() default {};

 

}

因此我们需要改动的位置有两处:

首先是注解的作用类,注解上指定groups属性 其次是controller中的请求的形参:在请求中形参的@Validated指定value值,也就是指定校验生效的分组,如果请求中的分组类型【@Validated的value值】和作用类中注解所指定的分组【@Phone中的groups属性的值】一致时,才会进行校验,否则不会执行校验

作用类:

?

1

2

3

4

5

6

7

8

9

10

@Data

@EqualsAndHashCode (callSuper = false )

@Accessors (chain = true )

public class Person implements Serializable {

  

   // 指定groups属性

   @Phone (groups = {Phone.A. class })

   private String phone;

 

}

controller层:

?

1

2

3

4

5

6

7

8

9

10

11

12

@RestController

@RequestMapping ( "/admin/" )

public class PersonController {

 

   @Autowired

   private PersonService personService;

 

   @PostMapping ( "/query" )

   public Person query( @RequestBody @Validated (Phone.A. class ) Person params) {

     return JsonResult.success(personService.queryByPhone(params));

   }

}

此时请求中的校验分组Phone.A.class和作用类中的校验分组Phone.A.class一致,所以校验会被执行

到此这篇关于java自定义注解验证手机格式的实现示例的文章就介绍到这了,更多相关java自定义注解验证手机格式内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

原文链接:https://blog.csdn.net/qq_44309181/article/details/114300078

查看更多关于java自定义注解验证手机格式的实现示例的详细内容...

  阅读:11次