Spring中验证base64字符串的注解

Alf*_*les 2 java validation rest spring javax-validation

我有一个休息服务,我的请求主体 bean 注释有 javax.validation 等,并且在一个特定字段中我收到一个编码为字符串 base64 的@NotBlank @NotNull @Pattern文件,

那么,是否有注释,或者我如何编写自定义验证注释,以便它检查字符串是否确实是 Base64 字符串?

我只需要以注释形式进行这样的验证:

try {
    Base64.getDecoder().decode(someString);
    return true;
} catch(IllegalArgumentException iae) {
    return false;
}
Run Code Online (Sandbox Code Playgroud)

提前谢谢

ker*_*ter 6

是的,您可以为它们编写自己的注释和验证器。

您的注释将如下所示:

@Documented
@Constraint(validatedBy = Base64Validator.class)
@Target( { ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface IsBase64 {
    String message() default "The string is not base64 string";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}
Run Code Online (Sandbox Code Playgroud)

约束验证器javax.validation实现(我在这里使用您的代码进行实际验证):

public class Base64Validator implements ConstraintValidator<IsBase64, String> {
    
    @Override
    public boolean isValid(String value, ConstraintValidatorContext cxt) {
        try {
            Base64.getDecoder().decode(value);
            return true;
        } catch(IllegalArgumentException iae) {
            return false;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

带有注释字段的示例数据类:

@Data
public class MyPayload {
    @IsBase64
    private String value;
}
Run Code Online (Sandbox Code Playgroud)

@Valid以及带有必需注释的控制器方法示例:

@PostMapping
public String test(@Valid @RequestBody MyPayload myPayload) {
    return "ok";
}
Run Code Online (Sandbox Code Playgroud)

更新:另外,如果你想检查 Fiven 字符串是否是 Base64 字符串,你可以使用isBase64()apache-commons libraby 中的方法,该类是org.apache.commons.codec.binary.Base64 So,它看起来像这样 Base64.isBase64(str);