JSR303校验框架介绍

一.JSR303 校验框架介绍:
  • 是javaEE开发的规范,JSR303 用于对JavaBean 中的字段的值进行验证,使得验证逻辑从业务代码中脱离出来.
  • 是一个运行时的数据验证框架,在验证之后验证的错误信息会被马上返回
二.JSR303 校验框架注解类:
  • @NotNull  注解元素必须是非空
  • @Null  注解元素必须是空
  • @Digits  验证数字构成是否合法
  • @Future  验证是否在当前系统时间之后
  • @Past  验证是否在当前系统时间之前
  • @Max  验证值是否小于等于最大指定整数值
  • @Min  验证值是否大于等于最小指定整数值
  • @Pattern  验证字符串是否匹配指定的正则表达式
  • @Size  验证元素大小是否在指定范围内
  • @DecimalMax  验证值是否小于等于最大指定小数值
  • @DecimalMin  验证值是否大于等于最小指定小数值
  • @AssertTrue 被注释的元素必须为true
  • @AssertFalse 被注释的元素必须为false
三.HibernateValidator 扩展
  • @Email 被注释的元素必须是电子邮箱地址

  • @Length 被注释的字符串的大小必须在指定的范围内

  • @NotEmpty 被注释的字符串的必须非空

  • @Range 被注释的元素必须在合适的范围内

四.使用自定义注解
package com.sugon.util;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;

/**
 * 当验证规格不能满足需求时,使用自定义注解
 * @author luoyuan
 * @create 2018-11-19-下午10:04
 */
@Documented
//自定义注解的实现类。
@Constraint(validatedBy= {ForbiddenValidator.class})
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)
@Repeatable(Forbidden.List.class)
public @interface Forbidden {

    //校验错误的默认信息
    String message() default "参数不正确";
    //分组
    Class<?>[]groups() default{};

    Class<? extends Payload>[] payload() default {};

    @Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE})
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @interface List{
        Forbidden[] value();
    };
}
package com.sugon.util;

/**
 * 自定义注解一定要实现ConstraintValidator接口奥,里面的两个参数
 * 第一个为 具体要校验的注解
 * 第二个为 校验的参数类型
 * @author luoyuan
 * @create 2018-11-19-下午10:15
 */
import org.springframework.util.StringUtils;
import javax.validation.*;
public class ForbiddenValidator implements ConstraintValidator<Forbidden,String>{

    private String[]forbiddenWords = {"admin","safeadmin"};
    初始化,得到注解数据
    @Override
    public void initialize(Forbidden constraintAnnotation) {
    }
    //自定义的数据验证判断
    @Override
    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
        if(StringUtils.isEmpty(value)){
            return true;
        }
        for(String word : forbiddenWords) {
            if(value.contains(word)){
                //验证失败
                return false;
            }
        }
        return true;
    }
}
五.与springboot结合使用
  • springboot默认整合了以上两种框架,无需导入任何jar

  • 实体类添加相应验证注解

package com.sugon.entity;

import com.sugon.util.Forbidden;
import lombok.Data;
import lombok.experimental.Accessors;
import org.hibernate.validator.constraints.Length;

import javax.validation.constraints.AssertFalse;
import javax.validation.constraints.DecimalMin;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Pattern;

/**
 *
 * @author luoyuan
 * @create 2018-11-19-下午10:00
 */
@Data  //次注解可自动生成set get 方法
@Accessors(chain = true) //次注解代表可以链式赋值
public class Demo {

    private final static String pattern = "^[a-zA-Z0-9_-]+$";

    //验证名称不能为空以及组成方式
    @NotEmpty(message="名字不能为空")
    @Pattern(regexp = pattern,message = "名字只有有大小写字母,数字和横线组成")
    //使用自定义验证规则
    @Forbidden(message = "系统关键字不能使用")
    private String name;

    //验证密码长度
    @Length(min =8,max=16, message ="密码长度应为8-16位")
    private String password;
    //验证年龄必须大于1
    @DecimalMin(value = "1",message = "年龄不合法")
    private Integer age;

    //验证必须为flase
    @AssertFalse(message = "必须为false")
    private Boolean isFalse;

    //验证身份证格式
    @Pattern(regexp = "^(\\d{18,18}|\\d{15,15}|(\\d{17,17}[x|X]))$", message = "身份证格式错误")
    private String idCard;


}

  • controller层配合@Valid注解以及BindingResult对象使用
package com.sugon.controller;

import com.sugon.entity.Demo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.validation.Valid;

/**
 *
 * @author luoyuan
 * @create 2018-11-19-下午10:30
 */
@RequestMapping("/user")
@Slf4j
public class UserController {

    @PatchMapping("/regist")
    public String regist(@Valid @RequestBody Demo demo,
                         BindingResult bindingResult){
        if (bindingResult.hasErrors()) {
            log.error("[用户注册] 参数不正确,form:{},message:{}", demo, bindingResult.getFieldError().getDefaultMessage());
            return bindingResult.getFieldError().getDefaultMessage();
        }
        return "success";
    }
}

Logo

瓜分20万奖金 获得内推名额 丰厚实物奖励 易参与易上手

更多推荐