javabean Validation校验框架快速使用

     javaweb 服务端需要对请求数据进行校验,不过编写校验代码繁琐费时重复劳动。发现可以使用Bean Validation框架进行数据校验,在此整理了一个快速使用教程。

基本使用

pom文件添加:

<dependency>
    <artifactId>hibernate-validator</artifactId>
    <groupId>org.hibernate</groupId>
    <version>6.0.16.Final</version>
</dependency>

javaBean代码:

public class User {
	private Integer userId;
	@NotEmpty(message = "用户名称不能为空")
	@Size(min=4,max = 16,message = "用户名称长度在4-16字符之间")
	private String userName;
	@NotNull(message = "城市不能为空")
	private Integer cityId;
	@NotEmpty(message = "手机号不能为空")
	@Pattern(regexp = "\\d{8,14}",message = "手机号格式不对")
    private String phone;
    
    //get and set   
}
	

 多层对象校验, 在成员变量使用注解@Valid

public class UserInfo{
  @Valid
  private User user;
  
  //get set
}

校验:

  ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();

  Validator validator = validatorFactory.getValidator();

  //装载校验对象并进行校验
  Set<ConstraintViolation<T>> resultSet = validator.validate(user);

  for (ConstraintViolation<T> violation : resultSet) {
      logger.error(violation.getMessage());
  }

spring mvc整合使用校验

@PostMapping("userAdd")
    public String userAdd(@Valid User user,@Valid UserInfo userInfo,BindingResult result) throws Exception {
        //校验结果封装在  BindingResult对象里
        if (result != null && result.hasErrors()) {
            return result.getAllErrors().stream().findFirst().get().getDefaultMessage();
        }
        //........
        return "ok";
    }

  注解类型

@Null验证   元素为null
@NotNull验证  元素为非null
@AssertTrue验证  元素为true
@AssertFalse验证  元素为false
@Min验证 元素大于等于@Min指定的value值
@Max验证 元素小于等于@max指定的value值
@NotBlank验证 元素不为  null或者 长度为0的字符
@NotEmpty验证  元素值不为 null ,字符串长度不为0、集合大小不为0
@DecimalMax验证  元素小于等于@ DecimalMax指定的value值
@DecimalMin验证  元素大于等于@ DecimalMin指定的value值
@Digits验证注解的元素值的整数位数(integer)和小数位数(fraction)上限
@Email验证  email格式
@Future验证  日期元素  晚于当前时间 
@FutureOrPresent验证  日期元素  是等于或晚于当前时间
@Negative验证 元素为负数
@NegativeOrZero验证 元素为负数或者0
@Past验证 日期元素 早于当前时间
@PastOrPresent验证 日期元素 等于或早于当前时间
@Pattern验证 元素 是否匹配正则表达式
@Positive验证 元素为正数
@PositiveOrZero验证 元素为正数或者0
@Size验证 元素在min和max(包含)指定区间之内,如字符长度、集合大小

 

分组和顺序验证

有时候新增和修改需要校验不同的字段,需要使用分组校验功能。并且在使用中需要进行自定义的顺序校验

定义分组接口和顺序:

@GroupSequence({ValidateGroups.A.class,
				ValidateGroups.B.class,
				ValidateGroups.C.class,
				ValidateGroups.D.class,
				ValidateGroups.E.class})
public interface ValidateGroups {

	public interface A{ }

	public interface B{ }

	public interface C{ }

	public interface D{ }

	public interface E{ }

}

javaBean 代码改造:

public class User {
	private Integer userId;
	@NotEmpty(message = "用户名称不能为空",groups = ValidateGroups.A.class)
	@Size(min=4,max = 16,message = "用户名称长度在4-16字符之间",groups = ValidateGroups.A.class)
	private String userName;
	@NotNull(message = "城市不能为空",groups = ValidateGroups.C.class)
	private Integer cityId;
	@NotEmpty(message = "手机号不能为空",groups = ValidateGroups.D.class)
	@Pattern(regexp = "\\d{8,14}",message = "手机号格式不对",groups =  ValidateGroups.D.class)
    private String phone;
    
    //get and set   
}
	

spring mvc  controller  改成用@Validated注解进行校验,并指定分组名称

@PostMapping("userAdd")
    public String userAdd(@Validated({ValidateGroups.class}) User user, BindingResult result) throws Exception {
        if (result != null && result.hasErrors()) {
            return result.getAllErrors().stream().findFirst().get().getDefaultMessage();
        }
        //........
        return "ok";
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值