我有以下用于驗證密碼的類。
public class PasswordConstraintValidator implements ConstraintValidator<ValidPassword, String> {
@Override
public void initialize(ValidPassword constraintAnnotation) {
}
@Override
public boolean isValid(String password, ConstraintValidatorContext context) {
PasswordValidator validator = new PasswordValidator(Arrays.asList(
// at least 8 characters
new LengthRule(8, 30),
// at least one upper-case character
new CharacterRule(EnglishCharacterData.UpperCase, 1),
// at least one lower-case character
new CharacterRule(EnglishCharacterData.LowerCase, 1),
// at least one digit character
new CharacterRule(EnglishCharacterData.Digit, 1),
// at least one symbol (special character)
new CharacterRule(EnglishCharacterData.Special, 1),
// no whitespace
new WhitespaceRule()
));
RuleResult result = validator.validate(new PasswordData(password));
if (result.isValid()) {
return true;
}
List<String> messages = validator.getMessages(result);
String messageTemplate = messages.stream().collect(Collectors.joining(","));
context.buildConstraintViolationWithTemplate(messageTemplate)
.addConstraintViolation()
.disableDefaultConstraintViolation();
return false;
}
}
@Documented
@Constraint(validatedBy = PasswordConstraintValidator.class)
@Target( {ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD, ElementType.LOCAL_VARIABLE, ElementType.TYPE_PARAMETER, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface ValidPassword {
String message() default "Invalid Password";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
為類中的欄位添加 @ValidPassword 注釋是可行的。但是,當我嘗試將注釋添加到函式中的引數時,驗證器永遠不會被呼叫/到達。
public void resetUserPassword(Integer userId, @ValidPassword String newPassword) {
}
在此處添加注釋也不起作用:
@PostMapping("/user/resetPassword/{id}")
public ResponseEntity<?> resetUserPassword(@PathVariable("userId") Integer userId, @Valid @ValidPassword @RequestBody String newPassword) {
userService.resetUserPassword(userId, newPassword)
return ResponseEntity.ok().build();
}
我不認為我缺少任何依賴項,所以我不確定問題出在哪里。
uj5u.com熱心網友回復:
在類級別注解中定義的注解@Validated是觸發特定 bean 開始的方法驗證所必需的。
換句話說
@Validated注解是一個類級別的注解,我們可以使用它來告訴 Spring 驗證傳遞給注解類的方法的引數。
請參閱此鏈接https://github.com/spring-projects/spring-framework/issues/11039找出來源@Validated
用法:
正如您使用以下方法與您的自定義注釋@ValidPassword一樣@Valid
@PostMapping("/user/resetPassword/{id}")
public ResponseEntity<?> resetUserPassword(@PathVariable("userId") Integer userId, @Valid @ValidPassword @RequestBody String newPassword) {
userService.resetUserPassword(userId, newPassword)
return ResponseEntity.ok().build();
}
@有效的
它用于啟用整個物件驗證正如您在下面的示例中看到的那樣@NotNull @Size,@NotBlank將呼叫 和 來驗證物件中存在的用戶輸入或提供的值。
例如:
public class DummyUser{
@NotNull
@Size(min =8)
private String password;
@NotBlank
private String username;
}
@已驗證
但是,根據您的情況,您希望在方法引數上呼叫自定義驗證,因此您需要向 spring 提供提示以呼叫自定義驗證。因此,要做到這一點,您必須@Validated在控制器中的類級別宣告注釋。
因此,這些是您在使用注釋對控制器類進行注釋后開始驗證的原因@Validated。
uj5u.com熱心網友回復:
您需要@Validated在控制器類或其他類上添加注釋,您希望在其中使用自定義驗證來驗證方法引數。
spring-boot 2.1.x 檔案中有關于這種方法級驗證的解釋,但我在當前的 2.7.x 檔案中找不到它。
一般來說,它是一個 spring-framework 功能,可以在這里找到。在非引導專案中,您需要MethodValidationPostProcessor手動創建一個型別的 bean,但 spring-boot 會為您自動配置該 bean - 自動配置可以在ValidationAutoConfiguration類中找到。
根據 java-docs ofMethodValidationPostProcessor,具有 JSR-303 約束注解方法的目標類需要@Validated在型別級別使用 Spring 的注解進行注解,以便在其方法中搜索行內約束注解。驗證組也可以通過指定@Validated。默認情況下,JSR-303 將僅針對其默認組進行驗證。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/513229.html
下一篇:啟動SpringBoot時出錯-無法自省類[org.springframework.security.config.annotation.web.configuration.WebSecurityCo
