SpringBoot优雅的对参数进行校验
什么是不优雅的参数校验
后端对前端传过来的参数也是需要进行校验的,如果在controller中直接校验需要用大量的if else做判断,以添加用户的接口为例,需要对前端传过来的参数进行校验, 如下的校验就是不优雅的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| @RestController @RequestMapping("/user") public class UserController {
@PostMapping("add") public ResponseEntity<String> add(User user) { if(user.getName()==null) { return ResponseResult.fail("user name should not be empty"); } else if(user.getName().length()<5 || user.getName().length()>50){ return ResponseResult.fail("user name length should between 5-50"); } if(user.getAge()< 1 || user.getAge()> 150) { return ResponseResult.fail("invalid age"); } return ResponseEntity.ok("success"); } }
|
针对这个普遍的问题,Java开发者在Java API规范 (JSR303) 定义了Bean校验的标准validation-api,但没有提供实现。
hibernate validation是对这个规范的实现,并增加了校验注解如@Email、@Length等。
Spring Validation是对hibernate validation的二次封装,用于支持spring mvc参数自动校验。
接下来,我们以springboot项目为例,介绍Spring Validation的使用
实现案列
加入依赖
1 2 3 4 5 6 7 8
| <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> </dependency>
|
请求参数封装
对每个参数字段添加validation注解约束和message
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| package com.example.springbootvalidation.entity;
import com.example.springbootvalidation.group.AddUserGroup; import com.example.springbootvalidation.group.EditUserGroup; import jakarta.validation.constraints.*; import lombok.Builder; import lombok.Data; import org.hibernate.validator.constraints.Length; import org.hibernate.validator.constraints.Range;
@Data @Builder public class User { private static final long serialVersionUID = 1L;
@NotEmpty(message = "could not be empty"controller中的接口使用校验时使用分组) private String userId;
@NotEmpty(message = "could not be empty") @Email(message = "invalid email") private String email;
@NotEmpty(message = "could not be empty") @Pattern(regexp = "^(\\d{6})(\\d{4})(\\d{2})(\\d{2})(\\d{3})([0-9]|X)$", message = "invalid ID") private String cardNo;
@NotEmpty(message = "could not be empty") @Length(min = 1, max = 10, message = "nick name should be 1-10") private String nickName;
@NotNull(message = "could not be empty") @Range(min = 0, max = 1, message = "sex should be 0-1") private int sex;
@Max(value = 100, message = "Please input valid age") private int age; }
|
Controller中获取参数绑定结果
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| package com.example.springbootvalidation.controller;
import com.example.springbootvalidation.entity.ResponseResult; import com.example.springbootvalidation.entity.User; import com.example.springbootvalidation.group.AddUserGroup; import com.example.springbootvalidation.group.EditUserGroup; import jakarta.validation.Valid; import lombok.extern.slf4j.Slf4j; import org.springframework.http.ResponseEntity; import org.springframework.validation.BindingResult; import org.springframework.validation.FieldError; import org.springframework.validation.ObjectError; 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;
import java.util.List;
@Slf4j @RestController public class UserController { @PostMapping("/addUser") public ResponseResult<String> add(@Validated @RequestBody User user, BindingResult bindingResult) { if (bindingResult.hasErrors()) { List<ObjectError> errors = bindingResult.getAllErrors(); errors.forEach(p -> { FieldError fieldError = (FieldError) p; log.error("Invalid Parameter : object - {},field - {},errorMessage - {}", fieldError.getObjectName(), fieldError.getField(), fieldError.getDefaultMessage()); }); return ResponseResult.fail("invalid parameter"); } return ResponseResult.success(); }
|
校验结果
POST访问添加User的请求
输出结果,后台输出参数绑定错误信息:(包含哪个对象,哪个字段,什么样的错误描述)
1 2 3 4
| 2024-05-07T21:51:28.371+08:00 ERROR 34844 --- [spring-boot-validation] [nio-8080-exec-2] c.e.s.controller.UserController : Invalid Parameter : object - user,field - cardNo,errorMessage - could not be empty 2024-05-07T21:51:28.371+08:00 ERROR 34844 --- [spring-boot-validation] [nio-8080-exec-2] c.e.s.controller.UserController : Invalid Parameter : object - user,field - userId,errorMessage - could not be empty 2024-05-07T21:51:28.371+08:00 ERROR 34844 --- [spring-boot-validation] [nio-8080-exec-2] c.e.s.controller.UserController : Invalid Parameter : object - user,field - nickName,errorMessage - could not be empty 2024-05-07T21:51:28.371+08:00 ERROR 34844 --- [spring-boot-validation] [nio-8080-exec-2] c.e.s.controller.UserController : Invalid Parameter : object - user,field - email,errorMessage - invalid email
|
分组校验
上面的例子中,其实存在一个问题,User既可以作为addUser的参数(id为空),又可以作为editUser的参数(id不能为空),这时候怎么办呢?分组校验登场
先定义分组(无需实现接口)
1 2 3 4
| public interface EditUserGroup { } public interface AddUserGroup { }
|
在User的userId字段添加分组
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| public class User implements Serializable { private static final long serialVersionUID = 1L;
@NotEmpty(message = "could not be empty",groups = {EditUserGroup.class}) private String userId;
@NotEmpty(message = "could not be empty") @Email(message = "invalid email") private String email;
@NotEmpty(message = "could not be empty") @Pattern(regexp = "^(\\d{6})(\\d{4})(\\d{2})(\\d{2})(\\d{3})([0-9]|X)$", message = "invalid ID") private String cardNo;
@NotEmpty(message = "could not be empty") @Length(min = 1, max = 10, message = "nick name should be 1-10") private String nickName;
@NotNull(message = "could not be empty") @Range(min = 0, max = 1, message = "sex should be 0-1") private int sex;
@Max(value = 100, message = "Please input valid age") private int age; }
|
controller中的接口使用校验时使用分组,注意:需要使用@Validated注解
1 2 3 4 5 6 7 8 9 10 11 12
| @PostMapping("/editUser") public ResponseResult<String> edit(@Validated({EditUserGroup.class}) @RequestBody User user, BindingResult bindingResult) { if (bindingResult.hasErrors()) { List<ObjectError> errors = bindingResult.getAllErrors(); errors.forEach(p -> { FieldError fieldError = (FieldError) p; log.error("Invalid Parameter : object - {},field - {},errorMessage - {}", fieldError.getObjectName(), fieldError.getField(), fieldError.getDefaultMessage()); }); return ResponseResult.fail("invalid parameter"); } return ResponseResult.success(); }
|
测试
1
| 2024-05-07T22:05:32.148+08:00 ERROR 35269 --- [spring-boot-validation] [nio-8080-exec-2] c.e.s.controller.UserController : Invalid Parameter : object - user,field - userId,errorMessage - could not be empty
|
@Validated和@Valid什么区别
在检验Controller的入参是否符合规范时,使用@Validated或者@Valid在基本验证功能上没有太多区别。但是在分组、注解地方、嵌套验证等功能上两个有所不同:
分组
@Validated:提供了一个分组功能,可以在入参验证时,根据不同的分组采用不同的验证机制,这个网上也有资料,不详述。@Valid:作为标准JSR-303规范,还没有吸收分组的功能。
注解地方
@Validated:可以用在类型、方法和方法参数上。但是不能用在成员属性(字段)上
@Valid:可以用在方法、构造函数、方法参数和成员属性(字段)上
嵌套类型
如果address是user的一个嵌套对象属性, 只能用@Valid
有哪些常用的校验
JSR303/JSR-349: JSR303是一项标准,只提供规范不提供实现,规定一些校验规范即校验注解,如@Null,@NotNull,@Pattern,位于javax.validation.constraints包下。JSR-349是其的升级版本,添加了一些新特性
@AssertFalse 被注释的元素只能为false
@AssertTrue 被注释的元素只能为true
@DecimalMax 被注释的元素必须小于或等于{value}
@DecimalMin 被注释的元素必须大于或等于{value}
@Digits 被注释的元素数字的值超出了允许范围(只允许在{integer}位整数和{fraction}位小数范围内)
@Email 被注释的元素不是一个合法的电子邮件地址
@Future 被注释的元素需要是一个将来的时间
@FutureOrPresent 被注释的元素需要是一个将来或现在的时间
@Max 被注释的元素最大不能超过{value}
@Min 被注释的元素最小不能小于{value}
@Negative 被注释的元素必须是负数
@NegativeOrZero 被注释的元素必须是负数或零
@NotBlank 被注释的元素不能为空
@NotEmpty 被注释的元素不能为空
@NotNull 被注释的元素不能为null
@Null 被注释的元素必须为null
@Past 被注释的元素需要是一个过去的时间
@PastOrPresent 被注释的元素需要是一个过去或现在的时间
@Pattern 被注释的元素需要匹配正则表达式"{regexp}"
@Positive 被注释的元素必须是正数
@PositiveOrZero 被注释的元素必须是正数或零
@Size 被注释的元素个数必须在{min}和{max}之间
hibernate validation:hibernate validation是对这个规范的实现,并增加了一些其他校验注解,如@Email,@Length,@Range等等
@CreditCardNumber 被注释的元素不合法的信用卡号码
@Currency 被注释的元素不合法的货币 (必须是{value}其中之一)
@EAN 被注释的元素不合法的{type}条形码
@Email 被注释的元素不是一个合法的电子邮件地址 (已过期)
@Length 被注释的元素长度需要在{min}和{max}之间
@CodePointLength 被注释的元素长度需要在{min}和{max}之间
@LuhnCheck 被注释的元素${validatedValue}的校验码不合法, Luhn模10校验和不匹配
@Mod10Check 被注释的元素${validatedValue}的校验码不合法, 模10校验和不匹配
@Mod11Check 被注释的元素${validatedValue}的校验码不合法, 模11校验和不匹配
@ModCheck 被注释的元素${validatedValue}的校验码不合法, ${modType}校验和不匹配 (已过期)
@NotBlank 被注释的元素不能为空 (已过期)
@NotEmpty 被注释的元素不能为空 (已过期)
@ParametersScriptAssert 被注释的元素执行脚本表达式"{script}"没有返回期望结果
@Range 被注释的元素需要在{min}和{max}之间
@SafeHtml 被注释的元素可能有不安全的HTML内容
@ScriptAssert 被注释的元素执行脚本表达式"{script}"没有返回期望结果
@URL 被注释的元素需要是一个合法的URL
@DurationMax 被注释的元素必须小于${inclusive == true ? '或等于' : ''}${days == 0 ? '' : days += '天'}${hours == 0 ? '' : hours += '小时'}${minutes == 0 ? '' : minutes += '分钟'}${seconds == 0 ? '' : seconds += '秒'}${millis == 0 ? '' : millis += '毫秒'}${nanos == 0 ? '' : nanos += '纳秒'}
@DurationMin 被注释的元素必须大于${inclusive == true ? '或等于' : ''}${days == 0 ? '' : days += '天'}${hours == 0 ? '' : hours += '小时'}${minutes == 0 ? '' : minutes += '分钟'}${seconds == 0 ? '' : seconds += '秒'}${millis == 0 ? '' : millis += '毫秒'}${nanos == 0 ? '' : nanos += '纳秒'}
spring validation:spring validation对hibernate validation进行了二次封装,在springmvc模块中添加了自动校验,并将校验信息封装进了特定的类中
自定义validation
如果上面的注解不能满足我们检验参数的要求,我们能不能自定义校验规则呢? 可以
定义注解
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| package com.example.springbootvalidation.annotation;
import jakarta.validation.Constraint; import jakarta.validation.Payload;
import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.*; import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE }) @Retention(RUNTIME) @Documented @Constraint(validatedBy = {TelephoneNumberValidator.class}) public @interface TelephoneNumber { String message() default "Invalid telephone number"; Class<?>[] groups() default { }; Class<? extends Payload>[] payload() default { }; }
|
定义校验器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| package com.example.springbootvalidation.annotation;
import jakarta.validation.ConstraintValidator; import jakarta.validation.ConstraintValidatorContext;
import java.util.regex.Pattern;
public class TelephoneNumberValidator implements ConstraintValidator<TelephoneNumber, String> { private static final String REGEX_TEL = "0\\d{2,3}[-]?\\d{7,8}|0\\d{2,3}\\s?\\d{7,8}|13[0-9]\\d{8}|15[1089]\\d{8}";
@Override public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) { try { return Pattern.matches(REGEX_TEL,s); } catch (Exception e) { return false; } } }
|
使用
1 2 3
| @TelephoneNumber(message = "invalid telephone number") private String telephone; }
|
源码地址:https://github.com/Breeze1203/JavaAdvanced/tree/main/springboot-demo/spring-boot-validation