SpringBoot Validation参数校验
本文为大家分享了SpringBoot集成Validation参数校验的具体代码,供大家参考。
1、依赖
SpringBoot在web启动器中已经包含validator包
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
非SpringBoot项目,需要自定引入依赖
<dependency> <groupId>org.hibernate.validator</groupId> <artifactId>hibernate-validator</artifactId> <version>6.1.5.Final</version> </dependency> <dependency> <groupOd>org.glassfish</groupId> <artifactId>jakarta.el</artifactId> <version>3.0.3</version> </dependency>
2、常用约束说明
package com.smile.project.validator.utils; public class 常用约束说明 { /** * @Null:元素为null * @NotNull:元素不为null * @AssertTrue:元素为true * @AssertFalse:元素为false * @Min(value):数字的值大于等于指定的最小值 * @Max(value):数字的值小于等于指定的最大值 * @DecimalMin(value):大数值大于等于指定的最小值 * @DecimalMax(value):大数值小于等于指定的最大值 * @Size(max=,min=):元素的大小在指定的范围内 * @Digits(integer,fraction):元素是一个数字,其值必须在可接受的范围内 * @Past:一个过去的日期 * @Future:一个将来的日期 * @Pattern(regex=,flag=):指定的正则表达式 * @URL:必须是一个URL * @Email:必须是email格式 * @NotBlank:字符串不能为空 * @NotEmpty:集合不能为空 * @Length:长度必须在指定范围内 * @Valid:对实体类进行校验 */ }
3、实体约束示例
import com.smile.project.validator.utils.Gender; import lombok.Data; import javax.validation.constraints.Email; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; @Data public class SysUser { private Long id; @NotNull(message = "用户名不能为空") @Size(min = 3,max = 5,message = "用户名长度为{min}-{max}之间") private String username; @NotNull(message = "昵称不能为空") private String name; @NotNull(message = "密码不能为空") private String password; @Email(message = "邮箱格式不合法") private String email; private String gender; }
4、控制层示例
需要在class加上@Validated注解
如果参数时实体,需要加上@Valid注解
import com.smile.project.validator.entity.SysUser; import org.springframework.http.ResponseEntity; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RestController; import javax.validation.Valid; import javax.validation.constraints.NotNull; @RestController @Validated public class SysUserController { /** * 方法参数为实体校验 */ @PostMapping("/register") public ResponseEntity register(@Valid SysUser sysUser){ return ResponseEntity.ok(sysUser); } /** * 方法参数校验 */ @GetMapping("user") public ResponseEntity getUser(@NotNull(message = "用户名不能为空") String username){ SysUser sysUser = new SysUser(); sysUser.setName("smile"); return ResponseEntity.ok(sysUser); } }
5、异常捕获
全局异常捕获,当出现参数校验不合法时捕获异常,并且返回给前端
import org.springframework.http.ResponseEntity; import org.springframework.validation.FieldError; import org.springframework.validation.ObjectError; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import javax.validation.ConstraintViolation; import javax.validation.ConstraintViolationException; import java.util.HashMap; import java.util.List; import java.util.Set; /** * 全局异常捕获 * 当出翔参数校验不合法时捕获异常,并且返回给前端 */ @ControllerAdvice public class GlobHandler { /** * 捕获方法参数校验异常 */ @ExceptionHandler(ConstraintViolationException.class) @ResponseBody public ResponseEntity constraintViolationExceptionHandler(ConstraintViolationException e){ Set<ConstraintViolation<?>> message = e.getConstraintViolations(); HashMap<String,Object> map = new HashMap<>(); message.stream().forEach(msg ->{ String path = msg.getPropertyPath().toString(); String field = path.substring(path.indexOf(".")+1); map.put(field,msg.getMessageTemplate()); }); return ResponseEntity.ok(map); } /** * 捕获实体参数校验异常 */ @ExceptionHandler(MethodArgumentNotValidException.class) @ResponseBody public ResponseEntity resolveMethodArgumentNotValidException(MethodArgumentNotValidException e){ List<ObjectError> allErrors = e.getBindingResult().getAllErrors(); HashMap<String,Object> map = new HashMap<>(); allErrors.stream().forEach(error -> { FieldError fieldError = (FieldError) error; map.put(fieldError.getField(),fieldError.getDefaultMessage()); }); return ResponseEntity.ok(map); } }
6、自定义校验规则
特殊的字段需要自定义规则,比如身份证号码,邮箱,电话等
6.1、定义校验注解
import com.smile.project.validator.utils.GenderValidator; import javax.validation.Constraint; import javax.validation.Payload; import java.lang.annotation.*; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.RetentionPolicy.RUNTIME; /** * 定义校验注解 */ @Target({METHOD,FIELD}) @Retention(RUNTIME) @Constraint(validatedBy = GenderValidator.class) @Documented public @interface Gender { String message() default "性别为男或者女"; Class<?>[] groups() default {}; Class<? extends Payload[]>[] payload() default {}; }
6.2、GenderValidator实现ConstraintValidator接口并提供校验规则
import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; /** * 实现ConstraintValidator接口并提供校验规则 */ public class GenderValidator implements ConstraintValidator<Gender,String> { //初始化校验值 @Override public void initialize(Gender constraintAnnotation) { } //检验规则 @Override public boolean isValid(String value, ConstraintValidatorContext content) { return "男".equals(value) || "女".equals(value); } }
6.3、在成员变量中使用注解
import com.smile.project.validator.utils.Gender; import lombok.Data; import javax.validation.constraints.Email; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; @Data public class SysUser { private Long id; @NotNull(message = "用户名不能为空") @Size(min = 3,max = 5,message = "用户名长度为{min}-{max}之间") private String username; @NotNull(message = "昵称不能为空") private String name; @NotNull(message = "密码不能为空") private String password; @Email(message = "邮箱格式不合法") private String email; @Gender() private String gender; }
7、分组校验
默认情况下,不指定分组都属于默认组;使用分组校验有利于分层校验开发
7.1、新建两个接口,一个用于查询,一个用于添加
public interface ADD extends Default { } public interface Select extends Default { }
7.2、修改尸体校验规则,如果不指定分组默认时Default组;
import com.smile.project.validator.utils.Gender; import lombok.Data; import javax.validation.constraints.Email; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; @Data public class SysUser { private Long id; @NotNull(message = "用户名不能为空",groups = ADD.class) @Size(min = 3,max = 5,message = "用户名长度为{min}-{max}之间") private String username; @NotNull(message = "昵称不能为空",groups = Select.class) private String name; @NotNull(message = "密码不能为空",groups = ADD.class) private String password; @Email(message = "邮箱格式不合法",groups = Select.class) private String email; @Gender() private String gender; }
7.3、控制层示例,此时只会校验ADD组和Default组
//分组校验 @PostMapping("/user") public ResponseEntity addUser(@Validated(value = ADD.class) @RequestBody SysUser sysUser){ return ResponseEntity.ok(sysUser); }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程宝库。
工作中需要把一些数据放到一个zip的压缩包中,可以使用 ZipOutputStream。ZipOutputStream可以将内容直接写入到zip包中。一般创建ZipOutputStream通常是先封 ...