gpt4 book ai didi

java - 多约束 Spring 验证

转载 作者:搜寻专家 更新时间:2023-11-01 02:37:04 30 4
gpt4 key购买 nike

我正在使用 spring 来验证表单。表单的模型与此类似:

public class FormModel {

@NotBlank
private String name;

@NotNull
@ImageSizeConstraint
private MultipartFile image;

}

“@ImageSizeConstraint”是自定义约束。我想要的是首先评估@NotNull,如果评估为假,则不评估@ImageSizeConstraint。

如果这不可能,我还必须检查自定义约束中的空值。这不是问题,但我想分开关注(不是 null/图像大小/图像/宽高比/等)。

最佳答案

您可以使用约束分组和分组序列来定义验证顺序。根据JSR-303 (3.5 部分。验证例程):

Unless ordered by group sequences, groups can be validated in no particular order. This implies that the validation routine can be run for several groups in the same pass.

作为 Hibernate validator documentation说:

In order to implement such a validation order you just need to define an interface and annotate it with @GroupSequence, defining the order in which the groups have to be validated (see Defining a group sequence). If at least one constraint fails in a sequenced group, none of the constraints of the following groups in the sequence get validated.

首先,您必须定义约束组并将它们应用于约束:

public interface CheckItFirst {}

public interface ThenCheckIt {}

public class FormModel {

@NotBlank
private String name;

@NotNull(groups = CheckItFirst.class)
@ImageSizeConstraint(groups = ThenCheckIt.class)
private MultipartFile image;
}

然后,由于约束的计算没有特定顺序,无论它们属于哪个组(Default 组),您必须创建 @GroupSequence用于您的 image 字段约束组。

@GroupSequence({ CheckItFirst.class, ThenCheckIt.class })
public interface OrderedChecks {}

你可以用

来测试它
Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
Set<ConstraintViolation<FormModel>> constraintViolations =
validator.validate(formModel, OrderedChecks.class);

要在 Spring MVC Controller 方法中应用此验证,您可以使用 @Validated注解,可以指定方法级验证的验证组:

@PostMapping(value = "/processFormModel")
public String processFormModel(@Validated(OrderedChecks.class) FormModel formModel) {
<...>
}

关于java - 多约束 Spring 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46524539/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com