问题描述
我想验证从客户端接收到的JSON请求.我尝试使用批注(@notnull, @length(min=1,max=8)
等),并且工作正常,但问题是我无法获取如果无效的字段和消息将被调用.虽然,但是我在控制台中收到一条错误消息.
I want to validate the JSON request which I am receiving from the client side.I have tried using the annotations (@notnull, @length(min=1,max=8)
, etc., etc.) and it is working fine but the problem is that I am not able to get the fields and messages which will be getting invoked if they are invalid.Although, I am getting an error message in my Console.
违反约束的列表:
[
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}'
}
]
询问是否有人可以帮助我,或者给我至少一种方法,以更有效的方式验证请求.
Request if anyone can help me on this or atleast give me an alternative to validate the request in a more efficient manner.
PS:我不想逐个字段对其进行验证.
PS: I don't want to validate it field by field.
推荐答案
您可以执行以下操作:说这是请求类:
You can do something like this:Say this is the request class:
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
}
然后,您可以编写自己的通用validate方法,该方法将给出不太冗长"的约束违反消息,如下所示:
Then, you can write your own generic validate method which will give a "less verbose" constraint violation message, like this:
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;
}
现在,您可以验证并检查您的请求是否包含任何错误.如果是,则可以将其打印(或发送回无效的请求消息).
Now, you can validate and check if your request contains any error or not. If yes, you can print it (or send back an invalid request message).
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
这篇关于如何在Spring Boot中验证JSON请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!