![](/img/trans.png)
[英]How do I use @NotEmpty constraint to validate an HTTP request body in Spring Boot?
[英]How do I validate the JSON request in Spring Boot?
我想验证我从客户端收到的 JSON 请求。 我已经尝试使用注释( @notnull, @length(min=1,max=8)
等)并且它工作正常但问题是我无法获取将如果它们无效,就会被调用。 尽管如此,我在控制台中收到一条错误消息。
违反约束的列表:
[
ConstraintViolationImpl
{
interpolatedMessage=
'must be greater than or equal to 900000000',
propertyPath=phoneNumber,
rootBeanClass=class
com.org.infy.prime.RestWithJPA.CarrierFile,
messageTemplate=
'{javax.validation.constraints.Min.message}'
}
ConstraintViolationImpl
{
interpolatedMessage=
'length must be between 1 and 20',
propertyPath=accountID,
rootBeanClass=class
com.org.infy.prime.RestWithJPA.CarrierFile,
messageTemplate=
'{org.hibernate.validator.constraints.Length.message}'
}
]
请求是否有人可以帮助我,或者至少给我一个替代方案,以更有效的方式验证请求。
PS:我不想逐个字段验证它。
你可以做这样的事情:说这是请求类:
public class DummyRequest {
@NotNull
private String code;
@NotNull
private String someField;
@NotNull
private String someOtherField;
@NotNull
private Double length;
@NotNull
private Double breadth;
@NotNull
private Double height;
// getters and setters
}
然后,您可以编写自己的通用验证方法,该方法将提供“不那么冗长”的约束违规消息,如下所示:
public static <T> List<String> validate (T input) {
List<String> errors = new ArrayList<>();
Set<ConstraintViolation<T>> violations = Validation.buildDefaultValidatorFactory().getValidator().validate(input);
if (violations.size() > 0) {
for (ConstraintViolation<T> violation : violations) {
errors.add(violation.getPropertyPath() + " " + violation.getMessage());
}
}
return errors;
}
现在,您可以验证并检查您的请求是否包含任何错误。 如果是,您可以打印它(或发回无效的请求消息)。
public static void main (String[] args) {
DummyRequest request = new DummyRequest();
request.setCode("Dummy Value");
List<String> validateMessages = validate(request);
if (validateMessages.size() > 0 ) {
for (String validateMessage: validateMessages) {
System.out.println(validateMessage);
}
}
}
Output:
--------
height may not be null
length may not be null
someField may not be null
someOtherField may not be null
breadth may not be null
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.