Spring中用于验证的base64字符串的注解

huangapple go评论69阅读模式
英文:

Annotation for validation base64 string in Spring

问题

我有一个使用javax.validation注解的请求体bean的REST服务,例如@NotBlank @NotNull @Pattern等等。在一个特定的字段中,我接收到一个以Base64字符串编码的文件。

因此,是否有一个注解,或者如何编写一个自定义验证注解,以便检查字符串是否确实是Base64字符串?

我只需要这样的验证以注解形式:

try {
    Base64.getDecoder().decode(someString);
    return true;
} catch(IllegalArgumentException iae) {
    return false;
}

提前感谢。

英文:

I have a rest service with my request body bean annotated with javax.validation like @NotBlank @NotNull @Pattern etc., and in one specific field I receive a file encoded as a string base64,

so, is there an annotation, or how could I write a custom validation annotation, so it would check if the string is really a base64 string?

I just need a validation like this in annotation form:

try {
    Base64.getDecoder().decode(someString);
    return true;
} catch(IllegalArgumentException iae) {
    return false;
}

thnx in advance

答案1

得分: 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 {};
}

约束验证器 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;
        }
    }
}

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

@Data
public class MyPayload {
    @IsBase64
    private String value;
}

以及使用 @Valid 注解的控制器方法示例:

@PostMapping
public String test(@Valid @RequestBody MyPayload myPayload) {
    return "ok";
}

更新
另外,如果您想要检查给定的字符串是否是 base64 字符串,您可以使用 apache-commons 库中的 org.apache.commons.codec.binary.Base64 类中的 isBase64() 方法。用法如下:

Base64.isBase64(str);
英文:

Yes, you could write your own annotations and validators for them.

Your annotation would look like this:

<!-- language: java -->
@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 {};
}

Constraint validator javax.validation implementation (I'm using here your code for the actual validation):

public class Base64Validator implements ConstraintValidator&lt;IsBase64, String&gt; {
    
    @Override
    public boolean isValid(String value, ConstraintValidatorContext cxt) {
        try {
            Base64.getDecoder().decode(value);
            return true;
        } catch(IllegalArgumentException iae) {
            return false;
        }
    }
}

Example data class with the annotated field:

@Data
public class MyPayload {
    @IsBase64
    private String value;
}

And controller method example with @Valid annotation which is required:

@PostMapping
public String test(@Valid @RequestBody MyPayload myPayload) {
    return &quot;ok&quot;;
}

UPDATED:
Also, if you want to check whether the fiven string is a base64 string, you can use the method isBase64() from apache-commons libraby, the class is org.apache.commons.codec.binary.Base64
So, it would look like this
Base64.isBase64(str);

huangapple
  • 本文由 发表于 2023年2月14日 05:46:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/75441493.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定