首页 > 解决方案 > 休眠验证器不适用于请求正文

问题描述

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

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

实体:

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
@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);

        }
    }

邮递员传递的 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"
    ]
}

标签: hibernatespring-boothibernate-validator

解决方案


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

还要检查如果您使用此输入会发生什么:

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

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

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

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

尝试这个:

@PostMapping({"/saveProduct"})

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


推荐阅读