java - 不验证@RequestParam required = false

标签 java spring validation spring-boot annotations

我创建了一个自定义 validator 注释,并且仅当 username 不为 null 时才使用它。我有一个端点,其中不需要 @RequestParam String 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 {};
}

validator :

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"
]

最佳答案

在您的自定义 validator 中,您只需执行 null 检查,如下所示:

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

这样,如果为空则接受,否则检查。 另外,如果您想在 null 值应返回 false 的其他地方重用此 validator ,您可以在要检查的字段顶部添加一个 @NotNull ,或者在 validator 注释中添加参数规定是否接受 null 值。

最新的方法可以如下完成:

@ExistAccountWithUsername 类:

public @interface ExistAccountWithUsername {


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

Class[] payload() default {};

boolean acceptNull() default true;

}

validator 类:

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


 }

现在,当您不想为此 validator 接受空值时,只需使用 @ExistAccountWithUsername(acceptNull = false) 而不是仅使用 @ExistAccountWithUsername

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

相关文章:

带有必填字段验证器的 asp.net 正则表达式验证器

UserDaoImpl 处的 java.lang.ExceptionInInitializerError。<clinit>(UserDaoImpl.java :71)

java - 获取 Apache-Tomcat 的错误 :JRE_HOME variable is not defined correctly when trying to run startup. bat

java - 如何使 JUnit assertThat() 使用下限通配符?

java - Java 和 postgres BigDecimal/numeric 值之间的差异

java - 无法解析 org.springframework.security.core.GrantedAuthority,即使它已下载/显示在项目库下

java - Spring 验证 - 避免重复的约束消息

javascript - 用一些东西代替 <span> 以有效的方式包裹 <ul>

php - mysql - 如果日期不与现有日期重叠,则将日期范围插入日期列

java - 使用 ROME 搜索 RSS 源