I am creating a web service in spring. I have a Params DTO that is nested in my OtherParentDTO. Each request can contain only certain fields in the Dto parameters. If the fields are present, then I need to do validation (basically a zero check). In the custom validator, I will indicate which fields should be checked 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 client request:
{"params": {"customerId": "b2cab997-df13-4cb0-8f67-4357b019bb96"}, "client": {}}
Update user request:
{"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;
}
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 Limit Checker
@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> {
@Override
public void initialize(IsValid constraintAnnotation) {
validateItems = constraintAnnotation.params();
}
@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) {
}
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())
return false
}
}
source
share