我有一个自定义 bean 验证器,它实现boolean isValid(Object, ConstraintValidatorContext)
了一些业务逻辑并根据该逻辑返回真/假。
我想做的是将一些数据添加到引发的 ConstraintViolation 异常中。任何捕获并处理它的异常处理程序都可以梳理出这些额外的数据,其中包括有关导致它的错误/参数的更多详细信息。现在我只能将一条消息与缺少这些动态细节的违规相关联。
例如,传入 isValid 的对象包含一个地图,其内容由验证器验证。因为验证器 API 只返回一个布尔值,所以我失去了映射的哪些成员触发了约束违规的粒度。我正在寻找某种方式来保存和传递这些信息。
编辑 8/13/2013 - 涉及 JAX-RS 的示例解决方案
(省略了一些与这个问题无关的 JAXB 细节)
FooParam.java
public class FooParam {
private Map<String, String> subParamMap;
public Map<String, String> getSubParamMap() { return this.subParamMap; }
public void setSubParamMap(Map<String, String> subParamMap) {
this.subParamMap = subParamMap;
}
public FooParam() { this.subParamMap = new HashMap<>(); }
}
FooResource.java
public class FooResource {
...
public void doSomething(@CheckValidParam(value=FooResoure.class) FooParam fooParam) {
...
}
}
CheckValidParam.java
@Target({ElementType.TYPE, ElementType.METHOD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = CheckValidParamValidator.class)
@Documented
public @interface CheckValidParam{
String message() default "{com.foo.bar.CheckValidParam.message}";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
Class<?> value();
@Target({ElementType.TYPE, ElementType.METHOD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@interface List {
CheckValidParam[] value();
}
}
CheckValidParamValidator.java
public class CheckValidParamValidator implements ConstraintValidator<CheckValidParam, FooParam> {
private Class<?> entityClass;
@Override
public void initialize(CheckValidParam checkValidParam ) {
this.entityClass = checkValidParam.value();
}
@Override
public boolean isValid(FooParam fooParam, ConstraintValidatorContext constraintValidatorContext) {
String message = constraintValidatorContext.getDefaultConstraintMessageTemplate();
constraintValidatorContext.disableDefaultConstraintViolation();
boolean isValid = true;
Map<String, String> subParamMap = fooParam.getSubParamMap();
for (Map.Entry<String, String> entry : subParamMap.entrySet()) {
//Contrived validation logic
if (entry.getValue().equalsIgnoreCase("junk")) {
constraintValidatorContext.buildConstraintViolationWithTemplate(message)
.addNode(entry.getKey()).addConstraintViolation();
isValid = false;
}
}
return isValid;
}
}
截获 JAX-RS 管道中抛出的 MethodConstraintViolationExceptions 的类的精简版本,以说明提取无效参数和相关的错误消息。
MethodConstraintValidationMapper.java
@Provider
public class MethodConstraintValidationMapperimplements ExceptionMapper<MethodConstraintViolationException> {
private static final Logger log = Logger.getLogger(MethodConstraintValidationMapper.class);
@Override
public Response toResponse(MethodConstraintViolationException ex) {
Response response;
Set<MethodConstraintViolation<?>> violations = ex.getConstraintViolations();
List<ValidationExceptionError> errors = new ArrayList<>();
for (MethodConstraintViolation<?> methodConstraintViolation : ex.getConstraintViolations()) {
ValidationExceptionError error = new ValidationExceptionError();
error.setFieldName(((PathImpl) methodConstraintViolation.getPropertyPath()).getLeafNode().asString());
error.setErrorMessage(methodConstraintViolation.getMessage());
errors.add(error);
}
return Response.status(Response.Status.PRECONDITION_FAILED).entity(new GenericEntity<List<ValidationExceptionError>>(errors) {}).type(MediaType.APPLICATION_JSON).build();
}
}