大连网站设计团队,设计一个网站要多少钱,品牌建设方案怎么写,wordpress播放本地视频spring-boot-starter-validation 是 Spring Boot 中用于支持数据验证的模块。它建立在 Java Validation API#xff08;JSR-380#xff09;之上#xff0c;提供了一种方便的方式来验证应用程序中的数据。以下是使用 spring-boot-starter-validation 的基本方法#xff1a; …spring-boot-starter-validation 是 Spring Boot 中用于支持数据验证的模块。它建立在 Java Validation APIJSR-380之上提供了一种方便的方式来验证应用程序中的数据。以下是使用 spring-boot-starter-validation 的基本方法
快速入门
1.添加依赖
在你的 Spring Boot 项目的 pom.xml 文件中添加以下依赖
dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-validation/artifactId
/dependency如果你使用 Gradle可以在 build.gradle 文件中添加
implementation org.springframework.boot:spring-boot-starter-validation2.创建验证规则
在需要进行数据验证的类中使用 Java Validation API 中的注解标记字段以定义验证规则。例如使用 NotBlank 来确保字段不为空
public class MyRequest {NotBlankprivate String name;/*** 1.NotNull不能为null但可以为empty(, , ) * 2.NotEmpty不能为null而且长度必须大于0 ( , )* 3.NotBlank只能作用在String上不能为null而且调用trim()后长度必须大于0(test) 即必须有实际字符* 复制代码*/NotBlank(message用户名不能为空)private String userName;NotBlank(message年龄不能为空)Pattern(regexp^[0-9]{1,2}$,message年龄不正确)private String age;AssertFalse(message 必须为false)private Boolean isFalse;/*** 如果是空则不校验如果不为空则校验*/Pattern(regexp^\\d{4}(-)(1[0-2]|0?\\d)\\1([0-2]\\d|\\d|30|31)$,message出生日期格式不正确)private String birthday;Pattern(regexp ^[M|F|U|m|f|u]{1}$)private String gender;Pattern(regexp ^(MS)?(MR)?(PRO)?(MRS)?(DOC)?$)private String civility;Size(min 1, message field names cant be empty)private ListString names new ArrayList();// Other fields and methods...
}这只是一个简单的例子Java Validation API 提供了许多其他注解如 NotNull、Min、Max、Email 等以满足各种验证需求。
3.在控制器中使用验证
在需要验证输入数据的地方通常是在 Spring MVC 的控制器中使用 Valid 注解来启用验证
RestController
public class MyController {PostMapping(/submit)public ResponseEntityString submit(Valid RequestBody MyRequest request) {// Process the validated requestreturn ResponseEntity.ok(Request is valid);}
}在上面的例子中Valid 注解用于告诉 Spring Boot 对 MyRequest 对象进行验证。如果验证失败将会抛出 MethodArgumentNotValidException 异常。
4.处理验证错误
若要处理验证错误可以使用 BindingResult 对象。修改控制器方法以接受 BindingResult 参数并检查是否有错误
RestController
public class MyController {PostMapping(/submit)public ResponseEntityString submit(Valid RequestBody MyRequest request, BindingResult bindingResult) {if (bindingResult.hasErrors()) {// Handle validation errorsreturn ResponseEntity.badRequest().body(Validation errors);}// Process the validated requestreturn ResponseEntity.ok(Request is valid);}
}这就是使用 spring-boot-starter-validation 的基本步骤。通过这种方式你可以方便地在 Spring Boot 应用程序中进行数据验证确保输入数据的合法性。
分组校验
在使用 Spring Boot Validation 进行分组校验时你可以使用 Validation API 提供的 GroupSequence 注解来定义校验顺序。下面是一个简单的示例演示如何在 Spring Boot 中实现分组校验。
首先假设你有一个包含分组信息的 Java Bean 类
import javax.validation.GroupSequence;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;public class MyRequest {// 定义分组public interface FirstGroup {}public interface SecondGroup {}// 定义分组顺序GroupSequence({FirstGroup.class, SecondGroup.class})public interface AllGroups {}// 分组校验示例NotNull(message ID不能为空, groups FirstGroup.class)private Long id;NotBlank(message 姓名不能为空, groups SecondGroup.class)private String name;NotNull(groups {FirstGroup.class, SecondGroup.class}, message 密码不能为空)private String password;// 省略其他字段和方法
}在上述示例中我们定义了两个分组 FirstGroup 和 SecondGroup然后使用 GroupSequence 注解定义了它们的顺序。接着在字段上使用 NotNull 和 NotBlank 注解并通过 groups 属性指定了校验时所属的分组。
接下来在你的控制器或服务中使用 Validated 注解来指定使用哪个分组进行校验
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;RestController
Validated
public class MyController {PostMapping(/submit)public String submit(Validated(MyRequest.FirstGroup.class) RequestBody MyRequest request) {// 处理请求return Request is valid;}PostMapping(/update)public String update(Validated(MyRequest.SecondGroup.class) RequestBody MyRequest request) {// 处理请求return Request is valid;}
}在上述示例中Validated 注解用于标记控制器然后在方法参数上使用 Validated 注解来指定使用哪个分组进行校验。在 /submit 接口中使用了 FirstGroup 进行校验而在 /update 接口中使用了 SecondGroup 进行校验。
这样你就可以实现基于分组的校验。请注意分组的顺序是在 GroupSequence 注解中定义的。 Validated与Valid 的区别 Validated提供了一个分组功能可以在入参验证时根据不同的分组采用不同的验证机制这个网上也有资料不详述。 Valid作为标准JSR-303规范还没有吸收分组的功能。 常用注解说明
在 Spring Boot 中用于数据验证的常用注解是来自 Java Validation APIJSR-380的注解。以下是一些常用的注解
通用注解
NotNull: 验证注解的元素值不是 null。Null: 验证注解的元素值是 null。AssertTrue: 验证注解的元素值是 true。AssertFalse: 验证注解的元素值是 false。Min(value): 验证注解的元素值大于等于指定的值。Max(value): 验证注解的元素值小于等于指定的值。Size(max, min): 验证注解的元素值的大小在指定的范围内。Digits(integer, fraction): 验证注解的元素值的整数部分和小数部分的数字不超过指定的数值。
字符串验证
NotBlank: 验证注解的元素值不为空不为 null、去掉前后空格后长度大于0。NotEmpty: 验证注解的元素值不为 null 且不为空。Email: 验证注解的元素值是一个有效的电子邮件地址。
数值验证
Positive: 验证注解的元素值是正数。PositiveOrZero: 验证注解的元素值是非负数。Negative: 验证注解的元素值是负数。NegativeOrZero: 验证注解的元素值是非正数。
日期和时间验证
Past: 验证注解的元素值是过去的日期或时间。PastOrPresent: 验证注解的元素值是过去或当前的日期或时间。Future: 验证注解的元素值是将来的日期或时间。FutureOrPresent: 验证注解的元素值是将来或当前的日期或时间。
自定义注解
你还可以创建自定义的注解通过实现 ConstraintValidator 接口来定义自己的验证逻辑并使用 Constraint 注解进行声明。
这些注解可以通过在 Java Bean 的字段上使用来进行数据验证。在 Spring Boot 中通常与 Valid 或 Validated 一起使用以触发验证。在上述提到的示例中已经展示了一些常用注解的使用方式。
示例 以下是常用定义校验的注解及其使用示例
NotNull被注解的元素必须不为null。例如
public class User {NotNull(message 姓名不能为空)private String name;// ...其他字段...
}NotEmpty被注释的对象必须不为空(数据:String,Collection,Map,arrays)。例如
public class User {NotEmpty(message 角色列表不能为空)private ListRole roles;// ...其他字段...
}NotBlankCharSequence子类型验证注解的元素值不为空包括不为null或去除首位空格后长度为0。例如
public class User {NotBlank(message 手机号码不能为空)private String phoneNumber;// ...其他字段...
}Min验证数字是否小于等于指定的最小值。例如
public class User {Min(value 18, message 年龄不能低于18岁)private int age;// ...其他字段...
}Max验证数字是否大于等于指定的最大值。例如
public class User {Max(value 60, message 年龄不能超过60岁)private int age;// ...其他字段...
}Pattern用于校验字符串是否符合指定的正则表达式。例如
public class User {Pattern(regexp ^\\d{6}$, message 身份证号码格式不正确)private String idCardNumber;// ...其他字段...
}Size用于限制字符序列如String、Collection、Map等的长度支持min和max属性。例如
public class User {Size(min 6, max 18, message 密码长度必须在6-18之间)private String password;// ...其他字段...
}Email用于校验邮箱地址。例如
public class User {Email(message 请输入正确的邮箱地址)private String email;// ...其他字段...
}Past用于判断日期是否在过去。例如
public class User {Past(message 生日不能晚于现在)private Date birthday;// ...其他字段...
}Future用于判断日期是否在未来。例如
public class User {Future(message 截止日期必须在未来)private Date deadline;// ...其他字段...
}DecimalMax验证数字是否小于等于指定的最大值。例如
public class User {DecimalMax(value 100.00, message 金额不能超过100元)private double amount;// ...其他字段...
}DecimalMin验证数字是否大于等于指定的最小值。例如
public class User {DecimalMin(value 1.00, message 价格不能低于1元)private double price;// ...其他字段...
}以上都是常见的数据校验注解使用这些注解可以让我们的应用程序具有更强的健壮性避免非法数据的输入。