自定義一個唯一字段校驗器
注解
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 "" ; // 不加這倆參數(shù) error msg: contains Constraint annotation, but does not contain a groups parameter. // 必須包含這兩個參數(shù) 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) { } /** * 通過該方法,對參數(shù)進行驗證,看是否通過。 * @param value 修飾字段的值。 * @param context 上下文 * @return true:驗證通過。 false:驗證不通過。 */ @Override public boolean isValid(String value, ConstraintValidatorContext context) { // 模擬數(shù)據(jù)庫判斷是否存在改用戶名 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(); } |
測試
總結(jié)
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關注服務器之家的更多內(nèi)容!
原文鏈接:https://blog.csdn.net/weixin_44912855/article/details/120110211