請求參數多層嵌套時與注解@RequestBody一起使用時就會產生 校驗失效問題
1. 請看代碼
@PostMapping("/addRole") public ResponseData<Boolean> addRole(@RequestBody @Validated RoleListParam roleParam) { return ResponseData.success(dramaService.addRole(roleParam)); }
2.參數嵌套
@ApiModel(value = "描述信息") @Data @Accessors(chain = true) public class RoleListParam { @ApiModelProperty("id") @NotNull(message = "id不能為空") private Long id; @ApiModelProperty("參數") private List<RoleParam> roleParamList; @ApiModelProperty("參數集合") private List<DramaDmParam> dmParams; }
3.深一層就不寫了
4.上述寫法 校驗不會生效
解決校驗問題
5.
1.看代碼
@ApiOperation("描述信息") @PostMapping("/addRole") public ResponseData<Boolean> addRole(@RequestBody @Valid RoleListParam roleParam) { return ResponseData.success(dramaService.addRole(roleParam)); }
2.嵌套數據中
@ApiModelProperty("id") @NotNull(message = "id不能為空") private Long dramaId; @ApiModelProperty("參數") @Valid private List<RoleParam> roleParamList; @ApiModelProperty("參數集合") @Valid private List<DramaDmParam> dmParams;
3.這樣寫校驗生效了需要我們在異常以攔截器中寫自定義攔截類
@ExceptionHandler(MethodArgumentNotValidException.class) public ResponseData<Object> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) { StringBuilder msg = new StringBuilder(); List<ObjectError> allErrors = e.getBindingResult().getAllErrors(); for (ObjectError allError : allErrors) { msg.append(allError.getDefaultMessage()); } return ResponseData.fail(ResponseCode.PARAM_INVALIDATE.getCode(), msg.toString()); }
注意:
BindException是@Validation單獨使用校驗失敗時產生的異常
MethodArgumentNotValidException是@RequestBody和@Validated配合時產生的異常,比如在傳參時如果前端的json數據里部分缺失@RequestBody修飾的實體類的屬性就會產生這個異常。