如何使用SpringMVC@Valid验证POST中的字段,以及PUT中的NOTNULL字段
我们正在使用SpringMVC创建一个RESTful API,我们有一个/products端点,在这里可以使用POST创建新产品并将其放入更新字段。我们还使用javax.validation来验证字段 In-POST可以正常工作,但In-PUT用户只能传递一个字段,而我不能使用@Valid,因此我需要用java代码为PUT复制使用注释进行的所有验证如何使用SpringMVC@Valid验证POST中的字段,以及PUT中的NOTNULL字段,spring,spring-mvc,bean-validation,Spring,Spring Mvc,Bean Validation,我们正在使用SpringMVC创建一个RESTful API,我们有一个/products端点,在这里可以使用POST创建新产品并将其放入更新字段。我们还使用javax.validation来验证字段 In-POST可以正常工作,但In-PUT用户只能传递一个字段,而我不能使用@Valid,因此我需要用java代码为PUT复制使用注释进行的所有验证 有人知道如何扩展@Valid注释并创建类似@ValidPresents或其他解决我问题的方法吗?您可以将验证组与Springorg.springfr
有人知道如何扩展@Valid注释并创建类似@ValidPresents或其他解决我问题的方法吗?您可以将验证组与Spring
org.springframework.validation.annotation.Validated
注释一起使用
Product.java
ProductController.java
有了此代码,
Product.code
、Product.name
和Product.price
将在创建和更新时进行验证<代码>产品.数量仅在更新时进行验证。如果实现接口验证程序以自定义验证,并通过反射检查任何类型的约束,该怎么办
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;
}
@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) { ... }
}