一篇文章教你如何用Java自定義一個參數校驗器
更新時間:2021年09月06日 11:05:34 作者:一月三千五
這篇文章主要介紹了使用java自定義一個參數校驗器,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習
自定義一個唯一字段校驗器
注解
@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 {}; // ----- }
校驗器
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); } }
異常處理
@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提供的用法完全一致
@Data public class User { @NotNull(message = "name不為null") @IsUnique(message = "用戶名是唯一的") private String name; @NotNull private String password; }
@PostMapping public String hello(@RequestBody @Valid User user) { return "hello" + user.getName(); }
測試
總結
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關注腳本之家的更多內容!
相關文章
SparkSQL使用IDEA快速入門DataFrame與DataSet的完美教程
本文給大家介紹使用idea開發(fā)Spark SQL 的詳細過程,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友參考下吧2021-08-08Spring Integration 實現消息驅動的詳細步驟
Spring Integration是一個用于構建消息驅動的中間件輕量級框架,它提供了一種模型和工具,用于在Spring應用程序中實現企業(yè)集成模式,這篇文章主要介紹了Spring Integration 實現消息驅動,需要的朋友可以參考下2024-05-05解決SpringBoot搭建MyBatisPlus中selectList遇到LambdaQueryWrapper報錯問題
這篇文章主要介紹了解決SpringBoot搭建MyBatisPlus中selectList遇到LambdaQueryWrapper報錯問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-01-01