【问题标题】:Hibernate Validator not working for request body休眠验证器不适用于请求正文
【发布时间】:2020-05-23 08:02:06
【问题描述】:

请检查下面的示例并帮助我。

我需要验证 productName、Description、Size 和 price,如果没有传递任何值,则需要通过实体中提供的消息获得错误响应。

实体:

Entity
@Table(name="products")
public class Products implements Serializable{

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    int productID;

    @NotNull(message="Name cannot be missing or empty")
    @Size(min=3, message="Name should have atleast 3 characters")
    String productName;

    @NotEmpty(message = "Please provide a description")
    String description;

    @NotNull(message = "Please provide a price")
    @Digits(integer = 10 /*precision*/, fraction = 2 /*scale*/)
    float price;

    @NotNull(message = "Size must not be empty")
    char size;

}

控制者:

@RequestMapping(value = "/saveProduct" ,method =RequestMethod.POST, produces = "application/json")
    public ResponseEntity<Object> saveProductController(@Valid @RequestBody Products prod) throws ProdDetailsNotFound, ProductAlreadyPresentException {
        System.out.println("Save");
        return new ResponseEntity<Object>(prodServ.saveProductService(prod), HttpStatus.CREATED); 

    }

ControllerAdvice:

@ControllerAdvice
@RestController
public class GlobalControllerAdvice extends ResponseEntityExceptionHandler{

     @Override
        protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
                                                                      HttpHeaders headers,
                                                                      HttpStatus status, WebRequest request) {

            Map<String, Object> body = new LinkedHashMap<>();
            body.put("timestamp", new Date());
            body.put("status", status.value());

            //Get all errors
            List<String> errors = ex.getBindingResult()
                    .getFieldErrors()
                    .stream()
                    .map(x -> x.getDefaultMessage())
                    .collect(Collectors.toList());

            body.put("errors", errors);

            return new ResponseEntity<>(body, headers, status);

        }
    }

在 Postman 中传递的 JSON:

{

    "productName":"aa",
    "description": ,
    "price":"200.00" ,
    "size": 

}

没有给出错误响应。

当我在下面尝试时

{

    "productName":"aa",
    "description": "asdasd",
    "price":"200.00" ,
    "size": "L"

} 

我得到了:

{
    "timestamp": "2020-05-23T07:51:30.905+00:00",
    "status": 400,
    "errors": [
        "Name should have atleast 3 characters"
    ]
}

【问题讨论】:

    标签: hibernate spring-boot hibernate-validator


    【解决方案1】:

    您是否真的使用:"description": ,"size": 作为第一个示例中的描述和大小输入值?您应该无法执行此请求,因为它构成了格式错误的 JSON 语法。我怀疑您应该在 Postman 中获得400 Bad Request 状态代码,因此请检查您收到的返回状态代码。

    如果你改用这个输入,还要检查会发生什么:

    {
        "productName": "aa",
        "description": "",
        "price": "200.00" ,
        "size": ""
    }
    

    此输入应为您提供您希望看到的错误消息。

    我怀疑第一个请求示例由于 400 状态码而根本没有得到处理,这意味着它甚至永远不会到达后端,因此没有消息。

    另外,而不是使用 @RequestMapping(value = "/saveProduct" ,method =RequestMethod.POST, produces = "application/json"),

    试试这个:

    @PostMapping({"/saveProduct"})
    

    它是上述的简写版本,使代码更具可读性。

    【讨论】:

      【解决方案2】:

      尝试在控制器上方添加@Validated。 就像一个更现代的方式来编写 Post 映射的例子:

      public interface EmployeeController {
          ResponseEntity<Employee> register(@Valid Employee employee);
      }
      
      @RestController
      @RequestMapping("/employee")
      @Validated
      public class EmployeeControllerImpl implements EmployeeController {
      
              @PostMapping(path = "/register",
                      consumes = "application/json",
                      produces = "application/json"
              )
              @Override
              public ResponseEntity<Employee> register(@RequestBody Employee employee) {
                  Employee registeredEmployee = service.register(employee);
                  return ResponseEntity.status(201).body(registeredEmployee);
              }
      }
      

      【讨论】:

      • 感谢团队,我发现了问题。发送 JSON DATA 时出现问题。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-30
      • 1970-01-01
      相关资源
      最近更新 更多