即使请求正文中存在错误,BindingResult也不会显示错误

时间:2019-08-07 04:37:56

标签: java rest spring-boot validation request-validation

我要验证传入的请求正文是否存在字段验证错误,但是BindingResult中没有捕获任何错误。

我已经尝试在DTO中使用@Valid注释以及约束注释,但是它不起作用。

这是我的控制器类

AdminController

@Slf4j
@RestController
@RequestMapping("/admin/staff")
@CrossOrigin("*")
public class AdminController {

  @Autowired
  private AdminService adminService;

  @PreAuthorize("hasAnyRole('ROLE_SUPER_ADMIN')")
  @PutMapping("/{id}")
  public ResponseEntity<GenericResponse<UserDetailsDTO>> updateUser(
      @PathVariable("id") String userId, @Valid @RequestBody
      GenericRequest<StaffUpdateRequestDTO> request, BindingResult bindingResult
  ) {
    exceptionDTO.setMessageId(request.getHeader().getMsgId());
    if(bindingResult.hasErrors()){
      throw ValidationError.builder().bindingResult(bindingResult).build();
    }
    if(!userId.equalsIgnoreCase(request.getTxnRequest().getUserDetails().getUserId())){
     throw ValidationError.builder().bindingResult(bindingResult).build();
    }
    GenericResponse<UserDetailsDTO> response = new GenericResponse<>();
    response.setHeader(adminUtil.createResponseHeader());
    response.getHeader().setMsgId(request.getHeader().getMsgId());
    response.getHeader().setChannelId(request.getHeader().getChannelId());
    response.setTxnResponse(adminService.saveUser(request.getTxnRequest()));
    return ResponseEntity.status(HttpStatus.OK).body(response);
  }

}

这里是DTO

GenericRequest

@Data
public class GenericRequest<T> {

  @NotNull(message = "Validation failure")
  private HeaderDTO header;

  @NotNull(message = "Validation failure")
  private T txnRequest;
}

HeaderDTO

@Data
public class HeaderDTO {

  @NotNull
  @NotEmpty
  private String msgId;

  @NotNull
  @NotEmpty
  private String timestamp;

  @NotNull
  @NotEmpty
  private String channelId;
}

StaffUpdateRequestDTO

@Data
public class StaffUpdateRequestDTO {

  @NotNull(message = "Validation failure")
  private UserDetailsDTO userDetails;

  @NotNull(message = "Validation failure")
  @NotEmpty(message = "Validation Failure")
  private String approvedBy;

}

UserDetailsDTO

@Data
public class UserDetailsDTO {

  @NotEmpty(message = "Validation failure")
  @NotNull(message = "Validation failure")
  private String userId;
  @NotEmpty(message = "Validation failure")
  @NotNull(message = "Validation failure")
  private String userName;
  @NotNull(message = "Validation failure")
  @NotEmpty(message = "Validation failure")
  private String emailId;
  @NotEmpty(message = "Validation failure")
  @NotNull(message = "Validation failure")
  private String countryCode;
  @NotNull(message = "Validation failure")
  private List<RoleDetailsDTO> roles;
}

RoleDetailsDTO

@Data
public class RoleDetailsDTO {

  @NotEmpty(message = "Validation failure")
  @NotNull(message = "Validation failure")
  private String roleId;
  @NotEmpty(message = "Validation failure")
  @NotNull(message = "Validation failure")
  private String roleName;
}

即使我没有从UserDetailsDTO发送一些字段,在下面的行中BindingResult错误检查也会失败:

if(bindingResult.hasErrors()){
      throw ValidationError.builder().bindingResult(bindingResult).build();
    }

已发送请求正文的示例:

{
    "header":{
        "msgId":"87612983612",
        "timestamp":"2019-08-05T12:12:12.122",
        "channelId":"BDSHK"
    },
    "txnRequest":{
        "userDetails":{
                "userId": "deepakkumarc",
                "userName": "Deepak Kumar Choudhary",
                "roles": [
                    {
                        "roleId": "SUPER_ADMIN",
                        "roleName": "SUPER ADMIN"
                    },
                    {
                        "roleId":"LI_PRODUCT_ADMIN",
                        "roleName":"LIFE INSURANCE PRODUCT ADMIN"
                    },
                    {
                        "roleId":"GI_PRODUCT_ADMIN",
                        "roleName":"GENERAL INSURANCE PRODUCT ADMIN"
                    }
                ]
        },
        "approvedBy":"deepakkumarc"
    }
}

如上所述,我没有发送emailId和countryCode,但是这通过了验证。期望是要在任何验证失败的情况下得到验证错误。

如何为该请求正文实施验证?

1 个答案:

答案 0 :(得分:0)

最后,我找出了问题所在。我们需要将@Valid放在字段级别上,如下所示:

@Data
public class StaffUpdateRequestDTO {

  @NotNull(message = "Validation failure")
  @Valid
  private UserDetailsDTO userDetails;

  @NotNull(message = "Validation failure")
  @NotEmpty(message = "Validation Failure")
  private String approvedBy;

}