好得很程序员自学网

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

一篇文章教你如何用Java自定义一个参数校验器

自定义一个唯一字段校验器

注解

?

1

2

3

4

5

6

7

8

9

10

11

12

13

@Target ({ElementType.FIELD})

@Retention (RetentionPolicy.RUNTIME)

@Documented

@Constraint (validatedBy = {IsUniqueValidator. class }) // 指定自定义的校验器

public @interface IsUnique {

     // 提示信息

     String message() default "" ;

     // 不加这俩参数 error msg: contains Constraint annotation, but does not contain a groups parameter.

     // 必须包含这两个参数

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

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

     // -----

}

校验器

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

public class IsUniqueValidator implements ConstraintValidator<IsUnique, String> {

     @Override

     public void initialize(IsUnique constraintAnnotation) {

     }

     /**

      * 通过该方法,对参数进行验证,看是否通过。

      * @param value   修饰字段的值。

      * @param context 上下文

      * @return true:验证通过。 false:验证不通过。

      */

     @Override

     public boolean isValid(String value, ConstraintValidatorContext context) {

         // 模拟数据库判断是否存在改用户名

         return ! "aaaa" .equals(value);

     }

}

异常处理

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

@ControllerAdvice

@ResponseBody

public class ValidatorExceptionHandler {

     @ExceptionHandler (value = BindException. class )

     public Map<String, String> exceptionHandler(BindException e) {

         List<ObjectError> allErrors = e.getAllErrors();

         StringBuilder sb = new StringBuilder();

         for (ObjectError error : allErrors) {

             sb.append(error.getDefaultMessage());

             sb.append( ", " );

         }

         String error = sb.toString();

         HashMap<String, String> resp = new HashMap<>();

         resp.put( "1004" , error.substring( 0 , error.lastIndexOf( "," )));

         return resp;

     }

}

使用, 跟spring提供的用法完全一致

?

1

2

3

4

5

6

7

8

@Data

public class User {

     @NotNull (message = "name不为null" )

     @IsUnique (message = "用户名是唯一的" )

     private String name;

     @NotNull

     private String password;

}

?

1

2

3

4

@PostMapping

public String hello( @RequestBody @Valid User user) {

     return "hello" + user.getName();

}

测试

总结

本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注的更多内容!

原文链接:https://blog.csdn.net/weixin_44912855/article/details/120110211

查看更多关于一篇文章教你如何用Java自定义一个参数校验器的详细内容...

  阅读:18次