spring字符串判空_Spring验证非空元素的字符串列表

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

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

@Override

public void initialize(NotEmptyFields notEmptyFields) {

}

@Override

public boolean isValid(List objects, ConstraintValidatorContext context) {

return objects.stream().allMatch(nef -> nef != null && !nef.trim().isEmpty());

}

}

Usage? Simple:

class QuestionPaper{

@NotEmptyFields

private List questionIds;

// getters and setters

}

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值