java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringBoot参数校验@Validated

SpringBoot参数校验之@Validated的使用详解

作者:IT利刃出鞘

这篇文章主要通过示例为大家详细介绍一下介绍了SpringBoot参数校验中@Validated的使用方法,文中的示例代码讲解详细,需要的可以参考一下

简介

说明

本文用示例说明SpringBoot的@Validated的用法。

依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

它里边依赖了hibernate validator,就是下边这个

<dependency>
    <groupId>org.hibernate.validator</groupId>
    <artifactId>hibernate-validator</artifactId>
</dependency>

用法1:不分组

跟上边“@Valid实例”的结果是一样的,只是把入参处的@Valid改为@Validated。

代码

Controller

package com.example.demo.validated.without_group.controller;
 
import com.example.demo.validated.without_group.entity.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
import javax.validation.Valid;
import java.util.List;
 
@Api(tags = "不分组")
@RestController
@RequestMapping("validatedWithoutGroup")
public class ValidatedWithoutGroupController {
 
    @ApiOperation("正常用法")
    @GetMapping("normal")
    public User normal(@Validated User user) {
        return user;
    }
 
    @ApiOperation("获得BindingResult")
    @GetMapping("bindingResult")
    public User bindingResult(@Validated User user, BindingResult bindingResult) {
        if (bindingResult.hasErrors()){
            List<ObjectError> list = bindingResult.getAllErrors();
            for (ObjectError objectError : list) {
                System.out.println(objectError.getDefaultMessage());
            }
            //System.out.println(bindingResult.getFieldError().getDefaultMessage());
        }
 
        return user;
    }
 
}

Entity

User类

package com.example.demo.validated.without_group.entity;
 
import lombok.Data;
 
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.List;
 
@Data
public class User {
    @NotBlank(message = "名字不能为空")
    private String name;
 
    private Integer age;
 
    @NotBlank(message = "密码不能为空")
    private String password;
 
    @NotEmpty(message = "分数不能为空")
    private List<Integer> scoreArray;
 
    @Valid
    @NotNull(message = "账户不能为null")
    private Account account;
}

Account类

package com.example.demo.validated.without_group.entity;
 
import lombok.Data;
 
import javax.validation.constraints.NotBlank;
 
@Data
public class Account {
    @NotBlank(message = "电话号码不能为空")
    private String phoneNumber;
 
    private String[] emails;
}

测试

测试1:缺少字段

postman访问:http://localhost:8080/validatedWithoutGroup/normal

postman结果:

后端结果:

2021-12-22 16:12:26.549  WARN 79176 --- [nio-8080-exec-7] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 3 errors
Field error in object 'user' on field 'scoreArray': rejected value [null]; codes [NotEmpty.user.scoreArray,NotEmpty.scoreArray,NotEmpty.java.util.List,NotEmpty]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.scoreArray,scoreArray]; arguments []; default message [scoreArray]]; default message [分数不能为空]
Field error in object 'user' on field 'password': rejected value [null]; codes [NotBlank.user.password,NotBlank.password,NotBlank.java.lang.String,NotBlank]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.password,password]; arguments []; default message [password]]; default message [密码不能为空]
Field error in object 'user' on field 'account': rejected value [null]; codes [NotNull.user.account,NotNull.account,NotNull.com.example.demo.validated.without_group.entity.Account,NotNull]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.account,account]; arguments []; default message [account]]; default message [账户不能为null]]

测试2:不缺少字段

postman访问:http://localhost:8080/validatedWithoutGroup/normal

postman结果:

测试3: 获得BindingResult

postman访问:http://localhost:8080/validatedWithoutGroup/bindingResult

postman结果:

后端结果:

分数不能为空
密码不能为空
账户不能为null

用法2:分组

代码

Controller

package com.example.demo.validated.with_group.controller;
 
import com.example.demo.validated.with_group.entity.User;
import com.example.demo.validated.with_group.validatation.IGroupA;
import com.example.demo.validated.with_group.validatation.IGroupAll;
import com.example.demo.validated.with_group.validatation.IGroupB;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
 
import java.util.List;
 
@Api(tags = "分组")
@RestController
@RequestMapping("validatedWithGroup")
public class ValidatedWithGroupController {
    @ApiOperation("使用组:GroupA")
    @GetMapping("groupA")
    public User groupA(@Validated({IGroupA.class}) User user) {
        return user;
    }
 
    @ApiOperation("使用组:GroupB")
    @GetMapping("groupB")
    public User groupB(@Validated({IGroupB.class}) User user) {
        return user;
    }
 
    @ApiOperation("使用组:GroupA和GroupB")
    @GetMapping("groupAAndGroupB")
    public User groupAAndGroupB(@Validated({IGroupA.class, IGroupB.class}) User user) {
        return user;
    }
 
    @ApiOperation("使用组:GroupAll")
    @GetMapping("groupAll")
    public User groupAll(@Validated({IGroupAll.class}) User user) {
        return user;
    }
 
}

Entity

User类

package com.example.demo.validated.with_group.entity;
 
import com.example.demo.validated.with_group.validatation.IGroupA;
import com.example.demo.validated.with_group.validatation.IGroupB;
import lombok.Data;
 
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.List;
 
@Data
public class User {
    @NotBlank(message = "名字不能为空")
    private String name;
 
    @NotNull(message = "年龄不能为空", groups = {IGroupA.class})
    private Integer age;
 
    @NotEmpty(message = "密码不能为空", groups = {IGroupB.class})
    private String password;
 
    @NotEmpty(message = "分数不能为空", groups = {IGroupA.class, IGroupB.class})
    private List<Integer> scoreArray;
 
    @Valid
    @NotNull(message = "账户不能为null")
    private Account account;
}

Account类

package com.example.demo.validated.with_group.entity;
 
import lombok.Data;
 
import javax.validation.constraints.NotEmpty;
 
@Data
public class Account {
    @NotEmpty(message = "电话号码不能为空")
    private String phoneNumber;
 
    private String[] emails;
}

Group

IGroupA接口

package com.example.demo.validated.with_group.validatation;
 
public interface IGroupA {
}

IGroupB接口 

package com.example.demo.validated.with_group.validatation;
 
public interface IGroupB {
}

IGroupAll接口 

package com.example.demo.validated.with_group.validatation;
 
import javax.validation.GroupSequence;
import javax.validation.groups.Default;
 
@GroupSequence({Default.class, IGroupA.class, IGroupB.class})
public interface IGroupAll {
}

测试

测试1:无参数请求groupA

postman访问:http://localhost:8080/validatedWithGroup/groupA

postman结果:

后端结果:

2021-12-22 16:32:44.138  WARN 85532 --- [nio-8080-exec-2] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 2 errors
Field error in object 'user' on field 'scoreArray': rejected value [null]; codes [NotEmpty.user.scoreArray,NotEmpty.scoreArray,NotEmpty.java.util.List,NotEmpty]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.scoreArray,scoreArray]; arguments []; default message [scoreArray]]; default message [分数不能为空]
Field error in object 'user' on field 'age': rejected value [null]; codes [NotNull.user.age,NotNull.age,NotNull.java.lang.Integer,NotNull]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.age,age]; arguments []; default message [age]]; default message [年龄不能为空]]

测试2:无参数请求groupB

postman访问:http://localhost:8080/validatedWithGroup/groupB

postman结果:

后端结果:

2021-12-22 16:33:15.773  WARN 85532 --- [nio-8080-exec-4] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 2 errors
Field error in object 'user' on field 'scoreArray': rejected value [null]; codes [NotEmpty.user.scoreArray,NotEmpty.scoreArray,NotEmpty.java.util.List,NotEmpty]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.scoreArray,scoreArray]; arguments []; default message [scoreArray]]; default message [分数不能为空]
Field error in object 'user' on field 'password': rejected value [null]; codes [NotEmpty.user.password,NotEmpty.password,NotEmpty.java.lang.String,NotEmpty]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.password,password]; arguments []; default message [password]]; default message [密码不能为空]]

测试3:无参数请求groupA和groupB

postman访问:http://localhost:8080/validatedWithGroup/groupAAndGroupB

postman结果:

后端结果:

2021-12-22 16:34:27.652  WARN 85532 --- [nio-8080-exec-6] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 3 errors
Field error in object 'user' on field 'scoreArray': rejected value [null]; codes [NotEmpty.user.scoreArray,NotEmpty.scoreArray,NotEmpty.java.util.List,NotEmpty]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.scoreArray,scoreArray]; arguments []; default message [scoreArray]]; default message [分数不能为空]
Field error in object 'user' on field 'age': rejected value [null]; codes [NotNull.user.age,NotNull.age,NotNull.java.lang.Integer,NotNull]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.age,age]; arguments []; default message [age]]; default message [年龄不能为空]
Field error in object 'user' on field 'password': rejected value [null]; codes [NotEmpty.user.password,NotEmpty.password,NotEmpty.java.lang.String,NotEmpty]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.password,password]; arguments []; default message [password]]; default message [密码不能为空]]

测试4:无参数请求groupAll

postman访问:http://localhost:8080/validatedWithGroup/groupAll

postman结果:

后端结果:

2021-12-22 16:36:54.095  WARN 91820 --- [nio-8080-exec-2] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 2 errors
Field error in object 'user' on field 'name': rejected value [null]; codes [NotBlank.user.name,NotBlank.name,NotBlank.java.lang.String,NotBlank]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.name,name]; arguments []; default message [name]]; default message [名字不能为空]
Field error in object 'user' on field 'account': rejected value [null]; codes [NotNull.user.account,NotNull.account,NotNull.com.example.demo.validated.with_group.entity.Account,NotNull]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.account,account]; arguments []; default message [account]]; default message [账户不能为null]]

可以看到:走的校验逻辑是没有除了IGroupA和IGroupB注解的字段的逻辑。

以上就是SpringBoot参数校验之@Validated的使用详解的详细内容,更多关于SpringBoot参数校验@Validated的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文