common-validation-starter
1.功能介绍
1.引入validation依赖
- 集成
spring-boot-starter-validation
,为项目提供注解校验功能。
2.排除默认日志依赖
- 排除
spring-boot-starter-logging
,避免与Log4j2
日志框架冲突,确保日志管理的灵活性和一致性。
2.案例演示
1.创建模块
2.目录结构
3.pom.xml
1.基本配置
xml
<!-- 通过properties来指定版本号 -->
<properties>
<!-- 指定编译版本 -->
<java.version>1.8</java.version>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<!-- 指定Sunrays-Framework的版本 -->
<sunrays.version>1.0.0</sunrays.version>
</properties>
<dependencyManagement>
<!-- 使用sunrays-dependencies来管理依赖,则依赖无需加版本号 -->
<dependencies>
<dependency>
<groupId>cn.sunxiansheng</groupId>
<artifactId>sunrays-dependencies</artifactId>
<version>${sunrays.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
2.引入依赖
xml
<dependencies>
<!-- common-validation-starter -->
<dependency>
<groupId>cn.sunxiansheng</groupId>
<artifactId>common-validation-starter</artifactId>
</dependency>
<!-- common-log4j2-starter 是必须引入的!!! -->
<dependency>
<groupId>cn.sunxiansheng</groupId>
<artifactId>common-log4j2-starter</artifactId>
</dependency>
<!-- 用来测试的Web模块 -->
<dependency>
<groupId>cn.sunxiansheng</groupId>
<artifactId>common-web-starter</artifactId>
</dependency>
</dependencies>
4.application.yml 配置日志根目录
yaml
sun-rays:
log4j2:
home: /Users/sunxiansheng/IdeaProjects/sunrays-framework-demo/common-validation-starter-demo/logs # 日志根目录(默认./logs)
5.JsrReq.java 使用注解进行参数校验
java
package cn.sunxiansheng.validation.entity;
import lombok.Data;
import javax.validation.Valid;
import javax.validation.constraints.*;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
/**
* Description: JSR-303校验请求参数
*
* @Author sun
* @Create 2024/10/28 11:16
* @Version 1.0
*/
@Data
public class JsrReq {
// 基础校验
@NotNull(message = "ID不能为空")
private Long id;
@NotBlank(message = "用户名不能为空")
@Size(min = 3, max = 20, message = "用户名长度必须在3到20个字符之间")
private String username;
@NotBlank(message = "电子邮件不能为空")
@Email(message = "电子邮件格式不正确")
private String email;
// 数值校验
@NotNull(message = "年龄不能为空")
@Min(value = 18, message = "年龄不能小于18岁")
@Max(value = 60, message = "年龄不能大于60岁")
private Integer age;
@NotNull(message = "薪资不能为空")
@DecimalMin(value = "5000.00", message = "薪资不能低于5000.00")
@DecimalMax(value = "100000.00", message = "薪资不能高于100000.00")
private BigDecimal salary;
// 日期校验
@NotNull(message = "生日不能为空")
@Past(message = "生日必须是过去的日期")
private Date birthDate;
@NotNull(message = "注册日期不能为空")
@PastOrPresent(message = "注册日期必须是过去或当前日期")
private Date registrationDate;
@NotNull(message = "有效期不能为空")
@FutureOrPresent(message = "有效期必须是未来或当前日期")
private Date expirationDate;
// 布尔校验
@AssertTrue(message = "必须接受条款")
private Boolean acceptedTerms;
@AssertFalse(message = "用户不能被封禁")
private Boolean isBanned;
// 字符串和正则表达式校验
@NotBlank(message = "密码不能为空")
@Pattern(regexp = "^[a-zA-Z0-9]{6,12}$", message = "密码必须是6到12位的字母或数字")
private String password;
// 集合校验
@NotEmpty(message = "电话号码列表不能为空")
private List<@Pattern(regexp = "^\\+?[0-9]{10,15}$", message = "电话号码格式不正确") String> phoneNumbers;
@NotEmpty(message = "技能标签不能为空")
@Size(min = 1, max = 5, message = "技能标签数量必须在1到5之间")
private List<@Size(min = 1, max = 20, message = "每个技能标签长度必须在1到20个字符之间") String> skillTags;
// 嵌套对象校验
@NotEmpty(message = "地址列表不能为空")
@Valid
private List<@Valid Address> addresses;
// 嵌套类:地址信息
@Data
public static class Address {
@NotBlank(message = "街道不能为空")
private String street;
@NotBlank(message = "城市不能为空")
private String city;
@NotBlank(message = "邮政编码不能为空")
@Pattern(regexp = "^[0-9]{5}$", message = "邮政编码必须是5位数字")
private String postalCode;
}
}
6.JsrController.java 获取校验结果的Controller
java
package cn.sunxiansheng.validation.controller;
import cn.sunxiansheng.tool.response.ResultWrapper;
import cn.sunxiansheng.validation.entity.JsrReq;
import cn.sunxiansheng.web.base.BaseController;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
/**
* Description: JSR-303校验控制器
*
* @Author sun
* @Create 2024/10/28 11:19
* @Version 1.0
*/
@RestController
public class JsrController extends BaseController {
@RequestMapping("/jsr")
public ResultWrapper<Map<String, String>> validate(@RequestBody @Valid JsrReq req, BindingResult result) {
if(result.hasErrors()){
Map<String,String> map = new HashMap<>();
//1、获取校验的错误结果
result.getFieldErrors().forEach((item)->{
//FieldError 获取到错误提示
String message = item.getDefaultMessage();
//获取错误的属性的名字
String field = item.getField();
map.put(field,message);
});
return ResultWrapper.fail(401, "参数校验失败", map);
}
return ResultWrapper.ok(null);
}
}
7.ValidationApplication.java 启动类
java
package cn.sunxiansheng.validation;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* Description: 启动类
*
* @Author sun
* @Create 2024/10/28 11:33
* @Version 1.0
*/
@SpringBootApplication
public class ValidationApplication {
public static void main(String[] args) {
SpringApplication.run(ValidationApplication.class, args);
}
}