Validation of a list of objects in Spring

后端 未结 12 1266
無奈伤痛
無奈伤痛 2020-11-28 05:30

I have the following controller method:

@RequestMapping(value=\"/map/update\", method=RequestMethod.POST, produces = \"application/json; charset=utf-8\")
@Re         


        
12条回答
  •  忘掉有多难
    2020-11-28 05:48

    I'm using spring-boot 1.5.19.RELEASE

    I annotate my service with @validated and then apply @Valid to the List parameter in the method and items in my list get validated.

    Model

    @Data
    @ApiModel
    @Validated
    public class SubscriptionRequest {
        @NotBlank()
        private String soldToBpn;
    
        @NotNull
        @Size(min = 1)
        @Valid
        private ArrayList dataProducts;
    
        private String country;
    
        @NotNull
        @Size(min = 1)
        @Valid
        private ArrayList contacts;
    }
    

    Service Interface (or use on concrete type if no interface)

    @Validated
    public interface SubscriptionService {
        List addSubscriptions(@NonNull @Size(min = 1) @Valid List subscriptionRequestList)
            throws IOException;
    }
    

    Global Exception Handler method (ApiError Type is not my design)

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = ConstraintViolationException.class)
    @ResponseBody
    public ApiError[] handleConstraintViolationException(ConstraintViolationException exception) {
        List invalidFields = exception.getConstraintViolations().stream()
            .map(constraintViolation -> new InvalidField(constraintViolation.getPropertyPath().toString(),
                                                         constraintViolation.getMessage(),
                                                         constraintViolation.getInvalidValue()))
            .collect(Collectors.toList());
        return new ApiError[] {new ApiError(ErrorCodes.INVALID_PARAMETER, "Validation Error", invalidFields)};
    }
    

    example bad method call from a controller

     LinkedList list = new LinkedList<>();
     list.add(new SubscriptionRequest());
     return subscriptionService.addSubscriptions(list);
    

    Response body (note the index [0])

    [
        {
            "errorCode": "invalid.parameter",
            "errorMessage": "Validation Error",
            "invalidFields": [
                {
                    "name": "addSubscriptions.arg0[0].soldToBpn",
                    "message": "may not be empty",
                    "value": null
                },
                {
                    "name": "addSubscriptions.arg0[0].dataProducts",
                    "message": "may not be null",
                    "value": null
                },
                {
                    "name": "addSubscriptions.arg0[0].contacts",
                    "message": "may not be null",
                    "value": null
                }
            ]
        }
    ]
    

提交回复
热议问题