添加绑定以进行验证

时间:2019-03-29 10:33:15

标签: java spring spring-restcontroller spring-rest

我想创建用于验证Java对象的Spring端点。我尝试实现此示例:

https://www.baeldung.com/validation-angularjs-spring-mvc

我尝试过:

public class WpfPaymentsDTO {

    @NotNull
    @Size(min = 4, max = 15)
    private String card_holder;

    private String card_number;
    ....
}

终点:

 @PostMapping(value = "/payment/{unique_transaction_id}", consumes = { MediaType.APPLICATION_JSON_VALUE }, produces = { MediaType.APPLICATION_JSON_VALUE })
      public ResponseEntity<StringResponseDTO> handleWpfMessage(@PathVariable("unique_transaction_id") String unique_transaction_id,
          @RequestBody WpfPaymentsDTO transaction, BindingResult result, HttpServletRequest request) throws Exception {

        if (result.hasErrors()) {
            List<String> errors = result.getAllErrors().stream()
              .map(DefaultMessageSourceResolvable::getDefaultMessage)
              .collect(Collectors.toList());
            return new ResponseEntity<>(errors, HttpStatus.OK);
        } 

        return ResponseEntity.ok(new StringResponseDTO("test"));
      }

在使用时提交Angular表单,我想验证所有字段。但目前我收到此错误:Cannot infer type arguments for ResponseEntity<>

实施此操作的适当理由是什么?

2 个答案:

答案 0 :(得分:2)

您在方法签名中缺少@Valid注释。 如果查看引用的示例,您将看到它已在User对象上使用。

所以在您的情况下:

@Valid @RequestBody WpfPaymentsDTO transaction

您还将在ResponseEntity<T>中返回两种不同的类类型

1)ResponseEntity<StringResponseDTO>在验证成功的情况下

2)ResponseEntity<List<String>>在验证失败的情况下

以上是原因:

  

但是当前我收到此错误:无法推断类型参数   ResponseEntity <>

如果您查看的是引用的示例,则方法的返回类型为ResponseEntity<Object>

因此您的方法应更改为:

  @PostMapping(value = "/payment/{unique_transaction_id}", 
     consumes = { MediaType.APPLICATION_JSON_VALUE }, 
     produces = { MediaType.APPLICATION_JSON_VALUE })
  public ResponseEntity<Object> handleWpfMessage(
                 @PathVariable("unique_transaction_id") String unique_transaction_id,
                 @Valid @RequestBody WpfPaymentsDTO transaction, 
                 BindingResult result, 
                 HttpServletRequest request) throws Exception {

更新:

  

有没有一种方法可以找出验证错误针对哪个变量   举起?

是的,您会收到如下所有字段绑定错误:

List<FieldError> errors = bindingResult.getFieldErrors();
for (FieldError error : errors ) {
    System.out.println ("Validation error in field: " + error.getField() 
                    + "! Validation error message: " + error.getDefaultMessage() 
                    + "! Rejected value:" + error.getRejectedValue());
}

答案 1 :(得分:1)

尝试使用Angular反应性表单(FormGroup和FormControl)。 我认为这样比较容易。