Spring REST如何以不同的方式验证请求体? [英] Spring REST how to validate request body in different ways?

查看:129
本文介绍了Spring REST如何以不同的方式验证请求体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 @Valid ,我们可以解析请求正文并使用 @NotEmpty ,<$ c等注释对其进行验证$ c> @Size(min = 5)。有没有办法有多种方法来验证身体?例如,在某些端点上,我想忽略一些验证器(在我的情况下, @NotNull )。

With @Valid we can parse the request body and validate it with annotations like @NotEmpty, @Size(min = 5). Is there a way to have multiples ways to validate the body? For example, on some endpoints, I would like to ignore some validators (@NotNull in my case).

我的想法是创建一个自定义注释,如 @ValidUnlessNull ,但是如何实现其解析器而无需执行 @RequestBody (我试图实现过滤器 HandlerMethodArgumentResolver )?

My guess was to create a custom annotation like @ValidUnlessNull, but how can I implement its resolver without having to do the job of @RequestBody (I tried to implement a Filter and a HandlerMethodArgumentResolver)?

推荐答案

您可以定义自定义验证组,并选择任何具有 @Validated 注释的组。

You can define custom validation groups and select any group with @Validated annotation.

1)定义空接口,用作验证组标识符:

1) Define empty interface, that will be used as validation group identifier:

public interface FirstValidateGroup{}

2)将验证注释绑定到指定的接口(组):

2) Bind validation annotation to specified interface (group):

public class Person{

    @NotBlank(groups = {FirstValidateGroup.class})
    private String firstName;
    @NotBlank
    private String lastName;

    //... getters and setters
}

请注意,您可以为一个属性绑定多个组。

Note, that you can bind multiple groups for one property.

3)使用 @Validated 注释选择验证组:

3) Select group of validation with @Validated annotation:

public ResponseEntity<Person> add(@Validated({FirstValidateGroup.class}) 
                                  @RequestBody Person person){
   ...
}

现在,只验证 firstName 属性。您可以在 @Validated 注释中指定多个组。

Now, only firstName property will be validated. You can specify multiple groups in @Validated annotation.

这篇关于Spring REST如何以不同的方式验证请求体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆