我遇到了一个场景,其中我有两个字段,例如CA和ID字段,我需要添加一个简单的检查,以确保CA和ID都不能为null,并且应该抛出一个错误消息,如400坏请求。然而,当一个字段为空而另一个字段不为空时,例如,当ID为空并且CA字段具有某个值时,它应该能够处理该请求,并且它应该发送200 ok用于该请求。
有人能为这种情况提出一种验证方法吗。
假设您有一个这样的模型:
public class Testmodel {
@NotNull(message = "MUST NOT BE NULL")
private int CA;
@NotNull(message = "MUST NOT BE NULL")
private int ID;
public Testmodel(@NotNull(message = "MUST NOT BE NULL") int CA, @NotNull(message = "MUST NOT BE NULL") int ID) {
this.CA = CA;
this.ID = ID;
}
public Testmodel() {
}
public int getCA() {
return CA;
}
public void setCA(int CA) {
this.CA = CA;
}
public int getID() {
return ID;
}
public void setID(int ID) {
this.ID = ID;
}}
然后你在你的验证两个字段,你需要做这样的事情:
import javax.validation.Validator;
private final Validator validator;
@Autowired
public YourClass(Validator validator) {
this.validator = validator;
}
HttpStatus testValidation() {
Testmodel testmodel = new Testmodel();
Set<ConstraintViolation<Testmodel>> violations = validator.validate(testmodel);
if (violations.isEmpty()) {
return HttpStatus.OK;
} else {
Map<String, Object> data = handleConstraintViolations(violations);
return HttpStatus.BAD_REQUEST;
}
}
private Map<String, Object> handleConstraintViolations(Set<ConstraintViolation<Testmodel>> violationsList) {
Map<String, Object> data = new HashMap<>();
for (ConstraintViolation<?> violation : violationsList) {
data.put(violation.getPropertyPath().toString(), violation.getMessage());
}
CustomValidationException ce = new CustomValidationException("Invalid fields!", data);
return data;
}
还要确保您的pom文件中有javax验证依赖项
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.0.Final</version>
</dependency>