【发布时间】: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