java Spring验证非空元素的字符串列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39504205/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 04:25:37  来源:igfitidea点击:

Spring Validate List of Strings for non empty elements

javaspringvalidationjava-8spring-validator

提问by Ravindra Ranwala

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.

我有一个包含字符串列表的模型类。该列表可以为空,也可以包含元素。如果它有元素,那些元素不能为空。例如,假设我有一个名为 QuestionPaper 的类,它有一个 questionIds 列表,其中每个都是一个字符串。

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

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.

论文可以有零个或多个问题。但是如果有问题,id 值不能是空字符串。我正在使用 SpringBoot、Hibernate、JPA 和 Java 编写微服务。我该如何进行此验证。任何帮助表示赞赏。

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

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

{ "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.

是否有任何开箱即用的方法来实现这一点,或者我是否必须为此编写自定义验证器。

回答by Branislav Lazic

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());
    }

}

Usage? Simple:

用法?简单的:

class QuestionPaper{

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

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

PS没有测试逻辑,但我想这很好。

回答by VinayVeluri

These might suffice the need, if it is only on null or empty space.

如果仅在 null 或空白空间上,这些可能就足够了。

@NotNull, @Valid, @NotEmpty

@NotNull, @Valid, @NotEmpty

You can check with example. Complete set of validations - JSR 303give an idea which suits the requirement.

您可以查看示例。完整的验证- JSR 303给出了适合需求的想法。

回答by Journeycorner

!CollectionUtils.isEmpty(questionIds) 
   && !questionIds.stream.anyMatch(StringUtils::isEmpty())

回答by Shweta Shaw

This can easily be addressed if you use

如果您使用,这可以轻松解决

import org.apache.commons.collections.CollectionUtils;

    QuestionPaper question = new QuestionPaper();
    question.setQuestionIds(Arrays.asList("", " ", "10103"));

   if(CollectionUtils.isNotEmpty(question.getQuestionIds())) {
        // proceed
    } else {
        //throw exception or return
    }

This will check for nontnull and notempty.

这将检查 nontnull 和 notempty。