我有一个REST端点,它接受请求主体中的一个对象和一个请求参数。当传递请求参数时,我需要验证对象的所有属性,如果不是参数采用指定的默认值,并且只需要验证2个属性。两种情况下的路径都需要相同。如何做到这一点?
目前,我已经检查了对象的模式、长度和可能值,并在注释的帮助下进行了验证。
-----更新类-------
@ValidateParent(parent = "parent ", child= "child")
public class anClass{
@NotNull(groups = {FrstValidator.class, SndValidator.class})
@Pattern(regexp = "^[a-zA-Z]{3}$",
groups = {FrstValidator.class, SndValidator.class})
String str1;
@NotNull(groups = {FrstValidator.class, SndValidator.class})
@Pattern(regexp = "^[a-zA-Z]{3}$",
groups = {FrstValidator.class, SndValidator.class})
String str2;
@Pattern(regexp = "^[a-zA-Z]{10}$",
groups = SndValidator.class)
String child;
@Pattern(regexp = "^[a-zA-Z]{10}$",
groups = SndValidator.class)
String parent;
@Pattern(regexp = "^[a-zA-Z]{10}$",
groups = SndValidator.class)
String str3;
}
ValidateParent
检查在请求主体中传递子级时是否也传递了父级。
您可以通过优雅的"弹簧方式";,使用验证组和两个独立的端点,通过请求参数的存在来区分:
验证组:
// Validation groups are just marker interfaces
private interface PartialValidation {}
private interface FullValidation {}
请求DTO:
@Data
private static class Request {
// This field will be validated only for FullValidation validation group
@NotNull(groups = FullValidation.class)
String field1;
// This field will be validated for both validation groups
@NotNull(groups = {FullValidation.class, PartialValidation.class})
String field2;
}
控制器:
// This endpoint is executed only if there is no myParam preprovided
@PostMapping(
value = "/validation",
params = "!myParam")
public void partialValidation(
@RequestParam(defaultValue = "DEFAULT") String myParam,
// Request is validated against the PartialValidation group
@RequestBody @Validated(PartialValidation.class) Request request) {
System.out.println("Partial validation");
}
// This endpoint is executed only if there is myParam preprovided
@PostMapping(
value = "/validation",
params = "myParam")
public void fullValidation(
@RequestParam String myParam,
// Request is validated against the FullValidation group
@RequestBody @Validated(FullValidation.class) Request request) {
System.out.println("Full validation");
}