我试图验证我的数据对象,但没有得到任何错误,即使无效的输入传递
下面的类用于违例检查。
package in.rps.validator;
import in.rps.exception.InvalidRequestException;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Set;
@Service
public class ObjectValidator {
private static final ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
private static final Validator validator = factory.getValidator();
public <T> void validate(Object o, Class<T> clazz) {
if (clazz.isInstance(o)){
T request = ((T) clazz);
Set<ConstraintViolation<T>> constraintViolations = validator.validate(request);
if (!constraintViolations.isEmpty()){
throw new InvalidRequestException();
}
}else{
throw new InvalidRequestException();
}
}
}
对象类
package in.rps.model.response;
import in.rps.model.Dispute;
import in.rps.model.Metadata;
import lombok.*;
import lombok.experimental.FieldDefaults;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@FieldDefaults(level = AccessLevel.PRIVATE)
public class DisputeHandleResponse {
@NotNull
Metadata metadata;
@NotNull
Response response;
@NotNull
Dispute dispute;
@NotNull
@Pattern(regexp = "^[a-zA-Z0-9]*$")
@Size(min =1, max = 35)
String requestId;
}
下面是我的Gradle依赖项。
compile("org.springframework.boot:spring-boot-starter-validation:2.3.7.RELEASE")
compile group: 'org.glassfish', name: 'javax.el', version: '3.0.1-b12'
compile group: 'javax.validation', name: 'validation-api', version: '2.0.1.Final'
我有多个数据对象需要根据需求进行验证,类似于上述数据对象。然而,问题是所有的约束验证都不能工作。
方法调用验证函数。
@CrossOrigin
@PostMapping(path = "/createRequest", produces = {MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<Object> createDispute(@RequestBody String request) {
Gson g = new Gson();
DisputeResponse d = g.fromJson(request, DisputeHandleResponse.class);
d.setRequestId(null);
objectValidator.validate(d, DisputeHandleResponse.class);
restService.process(uri, "dispute/create", request);
return ResponseEntity.ok().body(Acknowledgement.builder().build());
}
不确定我是否错过了什么。如有任何帮助,不胜感激。
问题现已修复。问题出在验证方法上。使用下面的方法就可以了。
public <T> void validate(Object o, Class<T> clazz) {
if (clazz.isInstance(o)){
Set<ConstraintViolation<T>> constraintViolations = validator.validate((T)o);
if (!constraintViolations.isEmpty()){
throw new InvalidRequestException();
}
}else{
throw new InvalidRequestException();
}
}
谢谢大家的宝贵意见。