本文实例为大家分享了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 常用约束说明 {
}
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;
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);
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程网。