Spring验证非空元素的字符串列表 [英] Spring Validate List of Strings for non empty elements

查看:337
本文介绍了Spring验证非空元素的字符串列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含字符串列表的模型类.该列表可以为空,也可以包含元素.如果具有元素,则这些元素不能为空.举例来说,假设我有一个名为QuestionPaper的类,该类具有一个questionId列表,每个列表都是一个字符串.

I have a model class which has list of Strings. The list can either be empty or have elements in it. If it has elements, those elements can not be empty. For an example suppose I have a class called QuestionPaper which has a list of questionIds each of which is a string.

class QuestionPaper{
private List<String> questionIds;
....
}

该论文可以有零个或多个问题.但是,如果有问题,则id值不能为空字符串.我正在使用SpringBoot,Hibernate,JPA和Java编写微服务.我该如何进行验证.感谢您的帮助.

The paper can have zero or more questions. But if it has questions, the id values can not be empty strings. I am writing a micro service using SpringBoot, Hibernate, JPA and Java. How can I do this validation. Any help is appreciated.

例如,我们需要拒绝来自用户的以下json输入.

For an example we need to reject the following json input from a user.

{ "examId": 1, "questionIds": [ "", " ", "10103" ] }

有没有现成的方法可以实现这一目标,或者我必须为此编写一个自定义验证器.

Is there any out of the box way of achieving this, or will I have to write a custom validator for this.

推荐答案

自定义验证批注应该不是问题:

Custom validation annotation shouldn't be a problem:

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = NotEmptyFieldsValidator.class)
public @interface NotEmptyFields {

    String message() default "List cannot contain empty fields";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

}


public class NotEmptyFieldsValidator implements ConstraintValidator<NotEmptyFields, List<String>> {

    @Override
    public void initialize(NotEmptyFields notEmptyFields) {
    }

    @Override
    public boolean isValid(List<String> objects, ConstraintValidatorContext context) {
        return objects.stream().allMatch(nef -> nef != null && !nef.trim().isEmpty());
    }

}

用法?简单:

class QuestionPaper{

    @NotEmptyFields
    private List<String> questionIds;
    // getters and setters
}

P.S.没有测试逻辑,但是我想这很好.

P.S. Didn't test the logic, but I guess it's good.

这篇关于Spring验证非空元素的字符串列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆