如何验证字符串集合和每个元素作为 URL?

我想验证Collection<String>. 每个元素都是一个 URL,我在表单中作为字符串获取。


@Valid

@URL

@ElementCollection 

public Collection<String> getPictures() {       

    return this.pictures;   

}


public void setPictures(final Collection<String> pictures) {         

      this.pictures = pictures;     

}

我想知道 Spring 中是否有一些注释可以让我验证这个集合中的所有字符串,比如 URL


MMTTMM
浏览 66回答 1
1回答

一只名叫tom的猫

没有直接验证该字段的注释。自定义注释的想法@URL是完全有效的,但您必须自己实现验证 - 注释只是“应该发生的事情”的标记。我建议你重命名@URL为@URLCollection以避免与类冲突java.net.URL。从定义注释开始。不要忘记注解@Constraint(查看其文档以了解如何正确定义自定义验证注解):@Target({ElementType.METHOD, ElementType.FIELD})@Retention(RetentionPolicy.RUNTIME)@Constraint(validatedBy = UrlCollectionValidator.class)&nbsp; &nbsp; &nbsp;// will be created belowpublic @interface URLCollection {&nbsp; &nbsp; String message() default "default error message";&nbsp; &nbsp; Class<?>[] groups() default {};&nbsp; &nbsp; Class<? extends Payload>[] payload() default {};}然后继续执行ConstraintValidator:public class UrlCollectionValidator implements ConstraintValidator<URLCollection, Collection<String>> {&nbsp; &nbsp; @Override&nbsp; &nbsp; public void initialize(URLCollectionconstraint) { }&nbsp; &nbsp; @Override&nbsp; &nbsp; public boolean isValid(Collection<String> urls, ConstraintValidatorContext context) {&nbsp; &nbsp; &nbsp; &nbsp; return // the validation logics&nbsp; &nbsp; }}嗯,就是这样。在 Spring 文档中的配置自定义约束中阅读有关此内容的更多信息:每个 bean 验证约束由两部分组成: *@Constraint声明约束及其可配置属性的注释。* 实现javax.validation.ConstraintValidator约束行为的接口的实现。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java