gpt4 book ai didi

spring - 如何使用 SpringMVC @Valid 验证 POST 中的字段且仅验证 PUT 中的非空字段

转载 作者:行者123 更新时间:2023-12-01 16:30:13 25 4
gpt4 key购买 nike

我们正在使用 SpringMVC 创建一个 RESTful API,并且我们有一个/products 端点,其中 POST 可用于创建新产品,并可使用 PUT 来更新字段。我们还使用 javax.validation 来验证字段。

在 POST 中工作正常,但在 PUT 中用户只能传递一个字段,并且我无法使用 @Valid,因此我需要使用 Java 代码为 PUT 复制使用注释进行的所有验证。

有人知道如何扩展 @Valid 注释并创建类似 @ValidPresents 的东西或其他可以解决我的问题的东西吗?

最佳答案

您可以将验证组与 Spring org.springframework.validation.annotation.Validated 一起使用注释。

Product.java

class Product {
/* Marker interface for grouping validations to be applied at the time of creating a (new) product. */
interface ProductCreation{}
/* Marker interface for grouping validations to be applied at the time of updating a (existing) product. */
interface ProductUpdate{}

@NotNull(groups = { ProductCreation.class, ProductUpdate.class })
private String code;

@NotNull(groups = { ProductCreation.class, ProductUpdate.class })
private String name;

@NotNull(groups = { ProductCreation.class, ProductUpdate.class })
private BigDecimal price;

@NotNull(groups = { ProductUpdate.class })
private long quantity = 0;
}

ProductController.java

@RestController
@RequestMapping("/products")
class ProductController {
@RequestMapping(method = RequestMethod.POST)
public Product create(@Validated(Product.ProductCreation.class) @RequestBody Product product) { ... }

@RequestMapping(method = RequestMethod.PUT)
public Product update(@Validated(Product.ProductUpdate.class) @RequestBody Product product) { ... }
}

使用此代码后,Product.code , Product.nameProduct.price将在创建和更新时进行验证。 Product.quantity但是,仅在更新时才会验证。

关于spring - 如何使用 SpringMVC @Valid 验证 POST 中的字段且仅验证 PUT 中的非空字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33741883/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com