我正在春天创建一个Web服务。我有一个Params DTO,它嵌套在我的OtherParentDTO中。每个请求可能只包含参数Dto中的某些字段。 如果字段存在,那么我需要进行验证(基本上是空检查)。在自定义验证器中,我将指定需要为特定请求验证哪些字段。我的问题是在控制器中错误字段作为参数返回。有没有办法将其更改为params.customerId或parmas.userId。
更新客户需求:
{" PARAMS" {"客户ID" :" b2cab997-df13-4cb0-8f67-4357b019bb96"},"客户":{}}
更新用户请求:
{" PARAMS" {"用户id" :" b2cab997-df13-4cb0-8f67-4357b019bb96"},"用户":{}}
@JsonSerialize(include = Inclusion.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class Params {
private String customerId;
private String userId;
//setter and getter are there
}
public class UpdateCustomerRequestDTO {
@NotNull
@IsValid(params = {"customerId"})
protected Params params;
@NotNull @Valid
private Customer customer;
}
public class UpdateUserRequestDTO {
@NotNull
@IsValid(params = {"userId"})
protected Params params;
@NotNull @Valid
private User user;
}
自定义约束验证器
@Constraint(validatedBy = {RequestParamsValidator.class})
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface IsValid {
String[] params() default "";
String message() default "{com.test.controller.validator.IsValid.message}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
public class RequestParamsValidator implements ConstraintValidator<IsValid, Params> {
/* (non-Javadoc)
* @see javax.validation.ConstraintValidator#initialize(java.lang.annotation.Annotation)
*/
@Override
public void initialize(IsValid constraintAnnotation) {
validateItems = constraintAnnotation.params();
}
/* (non-Javadoc)
* @see javax.validation.ConstraintValidator#isValid(java.lang.Object, javax.validation.ConstraintValidatorContext)
*/
@Override
public boolean isValid(Params value, ConstraintValidatorContext context) {
try {
for (String reqItem : validateItems) {
final Object curObj = PropertyUtils.getProperty(value, reqItem);
if (curObj == null || curObj.toString().isEmpty()) {
return false;
}
}
} catch (final Exception ignore) {
// ignore
}
return true;
}
}
控制器
@RequestMapping(method = RequestMethod.POST, value="", produces="application/json")
public @ResponseBody BaseResponseDTO updateCustomer(@RequestBody @Valid UpdateCustomerRequestDTO requestDTO,
BindingResult result) throws Exception {
if (result.hasErrors()) {
log.error("[Field] "+result.getFieldError().getField()+" [Message]"+ result.getFieldError().getDefaultMessage())
// But here the result.getFieldError().getField() is returning params. Is there any way with which I can change it to params.customerId/parmas.userId
return false
}
// add customer logic
}