如何验证List <list <string >>不为空?

时间:2019-05-20 20:27:46

标签: java spring validation annotations

我的实体中有一个List<List<String>>字段。在某个时候,我为此添加了一个新的字符串。

我试图创建一个自定义批注,但是由于某种原因,当我尝试提交表单时,它会引发错误。

我的注释(我在此处找到并修改过的List<String>使用了注释)

@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<List<String>>> {

    @Override
    public void initialize(NotEmptyFields notEmptyFields) {
    }

    @Override
    public boolean isValid(List<List<String>> lists, ConstraintValidatorContext context) {

        List<String> objects = lists.stream()
        .flatMap(Collection::stream)
        .collect(Collectors.toList());
        return objects.stream().allMatch(nef -> nef != null && !nef.trim().isEmpty());
    }

}

我的控制器部分:

    @RequestMapping(value = "/insert", method = { RequestMethod.POST })
    public ModelAndView insert(@ModelAttribute("sprav") @Valid Spravochnik sprav, ModelMap model, BindingResult bindingResult) {

        if(bindingResult.hasErrors()) {
            model.addAttribute("sprav", sprav);
            return new ModelAndView("insert", model);
        }

        if(spravochnikService.ins(sprav.getTableName(), sprav) == true) {

        model.addAttribute("tableName", sprav.getTableName());
        model.addAttribute("id", sprav.getId());

        return new ModelAndView("redirect:/spravochnik/list/{tableName}", model);
        }
        else {
            return new ModelAndView("error", model);
        }
    }

Spravochink是具有此复杂字段的结构。看起来像:

public class Spravochnik extends BaseEntity {

    private String tableName;
    private List<String> columnName;
    @NotEmptyFields
    private List<List<String>> valuesInRows;

    public Spravochnik() {

    }

    public String getTableName() {
        return tableName;
    }
    public void setTableName(String tableName) {
        this.tableName = tableName;
    }
    public List<String> getColumnName() {
        return columnName;
    }
    public void setColumnName(List<String> columnName) {
        this.columnName = columnName;
    }
    public List<List<String>> getValuesInRows() {
        return valuesInRows;
    }
    public void setValuesInRows(List<List<String>> valuesInRows) {
        this.valuesInRows = valuesInRows;
    }


0 个答案:

没有答案