How to use SpringMVC @Valid to validate fields in POST and only not null fields in PUT

亡梦爱人 提交于 2019-12-04 23:01:39

问题


We are creating a RESTful API with SpringMVC and we have a /products end point where POST can be used to create a new product and PUT to update fields. We are also using javax.validation to validate fields.

In POST works fine, but in PUT the user can pass only one field, and I can't use @Valid, so I will need to duplicate all validations made with annotation with java code for PUT.

Anyone knows how to extend the @Valid annotation and creating something like @ValidPresents or something else that solve my problem?


回答1:


You can use validation groups with the Spring org.springframework.validation.annotation.Validated annotation.

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) { ... }
}

With this code in place, Product.code, Product.name and Product.price will be validated at the time of creation as well as update. Product.quantity, however, will be validated only at the time of update.




回答2:


What if you implements the interface Validator to customize your validation and by reflection check your constraints for any Type.

8.2 Validation using Spring’s Validator interface



来源:https://stackoverflow.com/questions/33741883/how-to-use-springmvc-valid-to-validate-fields-in-post-and-only-not-null-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!