【问题标题】:Don't validate if @RequestParam required = false不验证 @RequestParam 是否需要 = false
【发布时间】:2018-08-23 21:51:16
【问题描述】:

我创建了一个自定义验证器注释,并且我只想在username 不为空时使用它。我有一个不需要@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"
]

【问题讨论】:

    标签: java spring validation spring-boot annotations


    【解决方案1】:

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

    @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;
    
    }
    

    验证器类:

    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

    【讨论】:

    • @Nikolas 我也想在其他情况下使用这个注释。我添加了带有布尔必填字段的参数,但我的注释有@NotNull@NotBlank 之类的注释,即使我在我的自定义验证器中return true,它们也会验证
    • 然后在这种情况下,您可以向 @ExistsAccountWithUsername 注释添加一个参数,以规定它应如何处理空值,如我的回答中所述。我将更新它以提供代码示例。
    • 我更新了答案,它现在应该适合您的用例
    • 我就是这样做的。查看我更新的代码和验证错误。如果required = false,我必须完全关闭验证,否则它会检查“打开”此注释的其他注释
    • 如果不需要@RequestParam,这并不意味着我应该传递空或空用户名,因为我会得到一个空指针异常,所以我需要检查@NotNull@NotBlank
    【解决方案2】:

    我看到您可能已经创建了验证注释@ExistAccountWithUsername。重用它并将条件添加到ConstraintValidator::isValid 方法中。

    @Override
    public boolean isValid(String username, ConstraintValidatorContext context) {
        if (username == null) {
            return true;  // is valid
        } else {
            // ... further validation in case the username is not null
        }
    }
    

    如果我误解了您的 @ExistAccountWithUsername 注释。 Baeldung的文章Method Constraints with Bean Validation 2.0有非常详细的指南。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-29
      • 1970-01-01
      • 1970-01-01
      • 2011-11-16
      • 2019-06-24
      • 2012-03-09
      • 2011-11-13
      相关资源
      最近更新 更多