我已经创建了一个自定义验证器注释,并且仅当username不为null时才想使用它。我有一个不需要@RequestParam String username的端点,那里一切都很好。注释存在问题,因为无论变量是否存在,它都会验证username。我只想验证username如果username存在。这是代码:

@RequestMapping(value = "", method = RequestMethod.GET)
public ResponseEntity get( @RequestParam(value = "username", required = false) @ExistAccountWithUsername(required = false) String username) {
    if (username != null) {
        return getUsersByUsername(username);
    }
    return getAllUsers();
}


注解:

@Filled
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = ExistAccountWithUsernameValidator.class)
public @interface ExistAccountWithUsername {
  boolean required() default true;
  String message() default "There is no account with such username";
  Class<?>[] groups() default {};
  Class<? extends Payload>[] payload() default {};
}


验证器:

public class ExistAccountWithUsernameValidator implements ConstraintValidator<ExistAccountWithUsername, String> {

  private UserService userService;
  private boolean required;

  public ExistAccountWithUsernameValidator(UserService userService) {
    this.userService = userService;
  }

  public void initialize(ExistAccountWithUsername constraint) {
    required = constraint.required();
  }

  public boolean isValid(String username, ConstraintValidatorContext context) {
    if (!required) {
        return true;
    }
    return username != null && userService.findByUsername(username).isPresent();
  }

}


编辑:我添加了参数。 @Filled@NotBlank@NotNull。更新的代码。它返回:

"errors": [
    "must not be blank",
    "must not be null"
]

最佳答案

在您的自定义验证器中,您可以执行空检查,如下所示:

@Override
public boolean isValid(String value, ConstraintValidatorContext context)
{
    if(value == null)
        return true;
    return someFurtherCheck(value, context);
}


这样,它将被接受是否为null,否则进行检查。
同样,如果您想在其他地方重复使用此验证器,而null值应返回false,则可以在要检查的字段上方添加@NotNull,也可以在验证器注释中添加规定null值应为的参数是否接受。

最新的方法可以按照以下步骤进行:

@ExistAccountWithUsername类别:

public @interface ExistAccountWithUsername {


String message() default "your message";
Class[] groups() default {};

Class[] payload() default {};

boolean acceptNull() default true;

}


ValidatorClass:

public class ExistAccountWithUsernameValidator implements ConstraintValidator<ExistAccountWithUsername, String> {

private boolean acceptNull;

@Override
public void initialize(ExistAccountWithUsername constraintAnnotation){
    acceptNull = constraintAnnotation.acceptNull();
}

@Override
public boolean isValid(String value, ConstraintValidatorContext context)
{
    if(value == null)
       return acceptNull;
    return someFurtherCheck(value, context);
}


 }


因此,现在当您不想接受此验证器的空值时,只需使用@ExistAccountWithUsername(acceptNull = false)而不是@ExistAccountWithUsername

关于java - 不验证@RequestParam是否必需= false,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51994768/

10-17 01:30