Java——实现json bean实体类的传参校验模板及注解详解

技术公众号:后端技术解忧铺
关注微信公众号:CodingTechWork,一起学习进步。

引言

  在java开发中,经常需要和外界系统进行参数对接,api设计中难免会遇到json传参不一致的情况,虽然纸面或者接口规范约束了应该怎么传参,仍然不可避免在对接过程中,出现传参不符合要求的,如传空值、传超过范围的值等。除了在Controllers层面使用@Validated或者@Valid注解外,本文将总结使用javax.validation.*;下的包进行校验的模板和常用的注解含义。

常用注解

注解 类型 说明
@NotNull 任意类型 验证注解的元素值不是null,但可以为empty
@NotEmpty CharSequence子类型(如String、StringBuilder、StringBuffer、CharBuffer)、Collection、Map、数组 验证注解的元素值不为null且size>0
@NotBlank 只能作用于字符串 验证注解的元素值不是null,且不能为空白空字符,如" ", 即该字符串调用trim()后,长度需大于0,才能验证通过
@Null 任意类型 验证注解的元素值是null
@Min(value=值) BigDecimal,BigInteger, byte,short, int, long,等任何Number或CharSequence(存储的是数字)子类型 验证注解的元素值大于等于指定的value值
@Max(value=值) BigDecimal,BigInteger, byte,short, int, long,等任何Number或CharSequence(存储的是数字)子类型 验证注解的元素值小于等于指定的value值
@Size(min=下限, max=上限) 字符串、Collection、Map、数组等 验证注解的元素值的在min和max(包含)指定区间之内,如字符长度、集合大小
@Range(min=最小值, max=最大值) BigDecimal,BigInteger,CharSequence, byte, short, int, long等原子类型和包装类型 验证注解的元素值在最小值和最大值之间
@Length(min=下限, max=上限) CharSequence子类型 验证注解的元素值长度在min和max区间内
@DecimalMin 这个约束的参数是一个通过BigDecimal定义的最小值的字符串表示.小数存在精度 验证注解的值不小于约束中指定的最小值
@DecimalMax(value=值) 这个约束的参数是一个通过BigDecimal定义的最大值的字符串表示.小数存在精度 验证注解的值不大于约束中指定的最大值
@Digits(integer=整数位数, fraction=小数位数) BigDecimal,BigInteger, byte,short, int, long,等任何Number或CharSequence(存储的是数字)子类型 integer为整数个数最大值,fraction为小数个数最大值
@AssertTrue 布尔类型 验证注解的元素值是true
@AssertFalse 布尔类型 验证注解的元素值是false
@Past java.util.Date,java.util.Calendar;Joda Time类库的日期类型 验证注解的元素值(日期类型)比当前时间早
@Future java.util.Date,java.util.Calendar;Joda Time类库的日期类型 验证注解的元素值(日期类型)比当前时间晚
@Email(regexp=正则表达式,flag=标志的模式) CharSequence子类型(如String等) 验证注解的元素值是Email,也可以通过regexp和flag指定
@Pattern(regexp=正则表达式,flag=标志的模式) String,任何CharSequence的子类型 验证注解的元素值与指定的正则表达式匹配

校验模板

程序

实体类示例

package com.example.andya.demo.bean;

import javax.validation.constraints.*;
import java.util.Date;
import java.util.List;

/**
 * @author andya
 * @date 2021/2/25
 */
public class PersonBean {

    @NotBlank(message = "name should not be blank")
    private String name;

    @NotNull(message = "alias should not be null")
    private List<String> alias;

    @Min(value = 1, message = "age should > 0")
    private int age;

    @Size(min = 11, max = 11, message = "telPhone's length should be 11")
    private String telPhone;

    @Email(message = "email should be valid")
    private String email;

    @AssertTrue(message = "isChinese should be true")
    private boolean isChinese;

    @Future(message = "futurePlanDate should be future")
    private Date futurePlanDate;

    @Past(message = "pastPlanDate should be past")
    private Date pastPlanDate;

 	@Digits(integer = 3, fraction = 2, message = "hight should be 3 integer and 2 fraction, (165.23)")
    private double hight;


    @Digits(integer = 2, fraction = 1, message = "weight should be 2 integer and 1 fraction, (60.5) kg")
    private String weight;


    public PersonBean() {
    }

    public String getWeight() {
        return weight;
    }

    public void setWeight(String weight) {
        this.weight = weight;
    }
    public double getHight() {
        return hight;
    }

    public void setHight(double hight) {
        this.hight = hight;
    }


    public Date getPastPlanDate() {
        return pastPlanDate;
    }

    public void setPastPlanDate(Date pastPlanDate) {
        this.pastPlanDate = pastPlanDate;
    }

    public Date getFuturePlanDate() {
        return futurePlanDate;
    }


    public void setFuturePlanDate(Date futurePlanDate) {
        this.futurePlanDate = futurePlanDate;
    }

    public boolean isChinese() {
        return isChinese;
    }

    public void setChinese(boolean chinese) {
        isChinese = chinese;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<String> getAlias() {
        return alias;
    }

    public void setAlias(List<String> alias) {
        this.alias = alias;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getTelPhone() {
        return telPhone;
    }

    public void setTelPhone(String telPhone) {
        this.telPhone = telPhone;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

模板示例

package com.example.andya.demo.service;

import com.example.andya.demo.bean.PersonBean;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author andya
 * @date 2021/2/25
 */
public class ValidParamsCheckService {



    /**
     * check bean params valid
     * @param t
     * @param <T>
     * @return
     */
    public static <T> Map<String, String> checkServiceParamsValid(T t) {
        Map<String, String> booleanStringMap = new HashMap<>();
        Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
        Set<ConstraintViolation<T>> violations = validator.validate(t);
        if (violations != null && violations.size() > 0) {
            StringBuilder stringBuilder = new StringBuilder();
            violations.forEach(
                    e -> stringBuilder.append(e.getMessage()).append(", "));
            booleanStringMap.put("valid", "false");
            booleanStringMap.put("message", stringBuilder.toString().substring(0, stringBuilder.length() - 2));
            return booleanStringMap;
        }
        booleanStringMap.put("valid", "true");
        booleanStringMap.put("message", "valid");
        return booleanStringMap;
    }


    public static void main(String[] args) throws ParseException {
        PersonBean personBean = new PersonBean();
        personBean.setName("");
        personBean.setAge(0);
        personBean.setEmail("fdsaf");
        personBean.setTelPhone("0123456789");
        personBean.setChinese(false);
        personBean.setFuturePlanDate(new Date());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        personBean.setPastPlanDate(simpleDateFormat.parse("2022-01-01 00:00:00"));
        personBean.setHight(165.2);
        personBean.setWeight("53.25");
        Map<String, String> map = checkServiceParamsValid(personBean);
        System.out.println("PersonBean check valid result map: " + map);


        PersonBean personBean1 = new PersonBean();
        personBean1.setName("小王");
        List<String> list = new ArrayList<>();
        list.add("王二");
        personBean1.setAlias(list);
        personBean1.setAge(1);
        personBean1.setEmail("xiaowang@163.com");
        personBean1.setTelPhone("01234567890");
        personBean1.setChinese(true);
        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        personBean1.setFuturePlanDate(simpleDateFormat1.parse("2022-01-01 00:00:00"));
        SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        personBean1.setPastPlanDate(simpleDateFormat2.parse("2021-01-01 00:00:00"));
        personBean1.setHight(165.23);
        personBean1.setWeight("53.2");
        Map<String, String> map1 = checkServiceParamsValid(personBean1);
        System.out.println("PersonBean check valid result map: " + map1);
    }
}

运行结果

PersonBean check valid result map: {valid=false, message=hight should be 3 integer and 2 fraction, (165.23) cm, telPhone's length should be 11, futurePlanDate should be future, weight should be 2 integer and 1 fraction, (60.5) kg, name should not be blank, age should > 0, pastPlanDate should be past, isChinese should be true, email should be valid, alias should not be null}

PersonBean check valid result map: {valid=true, message=valid}
posted @ 2021-02-25 21:01  Andya_net  阅读(1402)  评论(0编辑  收藏  举报