• SpringBoot--参数校验--@Validated--使用/实例


    原文网址:SpringBoot--参数校验--@Validated--使用/实例_IT利刃出鞘的博客-CSDN博客

    简介

    说明

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

     系列文章

    1. SpringBoot--参数校验--@Valid与@Validated的区别_IT利刃出鞘的博客-CSDN博客
    2. SpringBoot--参数校验--注解_IT利刃出鞘的博客-CSDN博客
    3. SpringBoot--参数校验--@Valid--使用/实例_IT利刃出鞘的博客-CSDN博客
    4. SpringBoot--参数校验--@Validated--使用/实例_IT利刃出鞘的博客-CSDN博客

    依赖

    1. <dependency>
    2. <groupId>org.springframework.boot</groupId>
    3. <artifactId>spring-boot-starter-validation</artifactId>
    4. </dependency>

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

    1. <dependency>
    2. <groupId>org.hibernate.validator</groupId>
    3. <artifactId>hibernate-validator</artifactId>
    4. </dependency>

    用法1:不分组

    代码

    Controller

    1. package com.example.demo.validated.without_group.controller;
    2. import com.example.demo.validated.without_group.entity.User;
    3. import io.swagger.annotations.Api;
    4. import io.swagger.annotations.ApiOperation;
    5. import org.springframework.validation.BindingResult;
    6. import org.springframework.validation.ObjectError;
    7. import org.springframework.validation.annotation.Validated;
    8. import org.springframework.web.bind.annotation.GetMapping;
    9. import org.springframework.web.bind.annotation.RequestMapping;
    10. import org.springframework.web.bind.annotation.RestController;
    11. import javax.validation.Valid;
    12. import java.util.List;
    13. @Api(tags = "不分组")
    14. @RestController
    15. @RequestMapping("validatedWithoutGroup")
    16. public class ValidatedWithoutGroupController {
    17. @ApiOperation("正常用法")
    18. @GetMapping("normal")
    19. public User normal(@Validated User user) {
    20. return user;
    21. }
    22. @ApiOperation("获得BindingResult")
    23. @GetMapping("bindingResult")
    24. public User bindingResult(@Validated User user, BindingResult bindingResult) {
    25. if (bindingResult.hasErrors()){
    26. List<ObjectError> list = bindingResult.getAllErrors();
    27. for (ObjectError objectError : list) {
    28. System.out.println(objectError.getDefaultMessage());
    29. }
    30. //System.out.println(bindingResult.getFieldError().getDefaultMessage());
    31. }
    32. return user;
    33. }
    34. }

    Entity

    User类

    1. package com.example.demo.validated.without_group.entity;
    2. import lombok.Data;
    3. import javax.validation.Valid;
    4. import javax.validation.constraints.NotBlank;
    5. import javax.validation.constraints.NotEmpty;
    6. import javax.validation.constraints.NotNull;
    7. import java.util.List;
    8. @Data
    9. public class User {
    10. @NotBlank(message = "名字不能为空")
    11. private String name;
    12. private Integer age;
    13. @NotBlank(message = "密码不能为空")
    14. private String password;
    15. @NotEmpty(message = "分数不能为空")
    16. private List<Integer> scoreArray;
    17. @Valid
    18. @NotNull(message = "账户不能为null")
    19. private Account account;
    20. }

    Account类

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

    测试

    测试1:缺少字段

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

    postman结果:

    后端结果:

    1. 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
    2. 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 [分数不能为空]
    3. 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 [密码不能为空]
    4. 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结果:

    后端结果:

    1. 分数不能为空
    2. 密码不能为空
    3. 账户不能为null

    用法2:分组

    代码

    Controller

    1. package com.example.demo.validated.with_group.controller;
    2. import com.example.demo.validated.with_group.entity.User;
    3. import com.example.demo.validated.with_group.validatation.IGroupA;
    4. import com.example.demo.validated.with_group.validatation.IGroupAll;
    5. import com.example.demo.validated.with_group.validatation.IGroupB;
    6. import io.swagger.annotations.Api;
    7. import io.swagger.annotations.ApiOperation;
    8. import org.springframework.validation.BindingResult;
    9. import org.springframework.validation.ObjectError;
    10. import org.springframework.validation.annotation.Validated;
    11. import org.springframework.web.bind.annotation.*;
    12. import java.util.List;
    13. @Api(tags = "分组")
    14. @RestController
    15. @RequestMapping("validatedWithGroup")
    16. public class ValidatedWithGroupController {
    17. @ApiOperation("使用组:GroupA")
    18. @GetMapping("groupA")
    19. public User groupA(@Validated({IGroupA.class}) User user) {
    20. return user;
    21. }
    22. @ApiOperation("使用组:GroupB")
    23. @GetMapping("groupB")
    24. public User groupB(@Validated({IGroupB.class}) User user) {
    25. return user;
    26. }
    27. @ApiOperation("使用组:GroupA和GroupB")
    28. @GetMapping("groupAAndGroupB")
    29. public User groupAAndGroupB(@Validated({IGroupA.class, IGroupB.class}) User user) {
    30. return user;
    31. }
    32. @ApiOperation("使用组:GroupAll")
    33. @GetMapping("groupAll")
    34. public User groupAll(@Validated({IGroupAll.class}) User user) {
    35. return user;
    36. }
    37. }

    Entity

    User类

    1. package com.example.demo.validated.with_group.entity;
    2. import com.example.demo.validated.with_group.validatation.IGroupA;
    3. import com.example.demo.validated.with_group.validatation.IGroupB;
    4. import lombok.Data;
    5. import javax.validation.Valid;
    6. import javax.validation.constraints.NotBlank;
    7. import javax.validation.constraints.NotEmpty;
    8. import javax.validation.constraints.NotNull;
    9. import java.util.List;
    10. @Data
    11. public class User {
    12. @NotBlank(message = "名字不能为空")
    13. private String name;
    14. @NotNull(message = "年龄不能为空", groups = {IGroupA.class})
    15. private Integer age;
    16. @NotEmpty(message = "密码不能为空", groups = {IGroupB.class})
    17. private String password;
    18. @NotEmpty(message = "分数不能为空", groups = {IGroupA.class, IGroupB.class})
    19. private List<Integer> scoreArray;
    20. @Valid
    21. @NotNull(message = "账户不能为null")
    22. private Account account;
    23. }

    Account类

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

    Group

    IGroupA接口

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

    IGroupB接口 

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

     IGroupAll接口 

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

    测试

    测试1:无参数请求groupA

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

    postman结果:

    后端结果:

    1. 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
    2. 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 [分数不能为空]
    3. 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结果:

    后端结果:

    1. 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
    2. 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 [分数不能为空]
    3. 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结果:

    后端结果:

    1. 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
    2. 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 [分数不能为空]
    3. 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 [年龄不能为空]
    4. 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结果:

    后端结果:

    1. 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
    2. 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 [名字不能为空]
    3. 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注解的字段的逻辑。

  • 相关阅读:
    选择困难?我如何实现可道云KODBOX与KODEXPLORE共存。
    基于ssm的BBS社区论坛系统
    【数据结构和算法】-贪心算法
    在Golang中依赖注入-wire篇
    数据的存储--MongoDB文档存储
    reg[0:3] 与reg[3:0] 流水灯
    【Vue3】自定义指令
    树与图的深度优先遍历:AcWing 846. 树的重心
    VR全景如何助力乡村振兴,VR全景推动农业发展
    Spring学习笔记(七)SpringMVC入门
  • 原文地址:https://blog.csdn.net/feiying0canglang/article/details/125493463