文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

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

2024-04-02 19:55

关注

简介

说明

本文用示例说明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的资料请关注编程网其它相关文章!

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     813人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     354人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     318人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     435人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     224人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-后端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯