I am creating a webservice in spring. I have a Params DTO which is nested in my OtherParentDTO's. Each request may contain only certain fields in the params Dto. If the fields are present then I need to do a validation(basically null check). In the custom validator I ll specify which fields needs to be validated for a particular request. My problem is in the controller the error field is returned as params. Is there any way to change it to params.customerId or parmas.userId.
Update customer req:
{"params":{"customerId" : "b2cab997-df13-4cb0-8f67-4357b019bb96"}, "customer":{}}
Update user req:
{"params":{"userId" : "b2cab997-df13-4cb0-8f67-4357b019bb96"}, "user":{}}
@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;
}
Custom constrain validator
@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;
}
}
Controller
@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
}