我创建了一个自定义 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/