当前位置: 首页 > 工具软件 > OVal > 使用案例 >

Java后端校验框架oval与hibernatevalidator的使用

松鸣
2023-12-01

1 oval
1)Oval 官方地址: http://oval.sourceforge.net/

2)依赖

<dependency>
    <groupId>net.sf.oval</groupId>
    <artifactId>oval</artifactId>
    <version>1.81</version>
</dependency>

3)常用注解
字符类型
@AsserURL、@Email、@Length、@MaxLength、@MinLength
@NotNull、@NotBlank、@NotEmpty、
@Digits、@HasSubstring
数值类型
@Range、@Max、@Min、@NotNegative
布尔类型
@AssertFalse、@AssertTrue
集合数组
@Size、@MaxSize、@MinSize、@MemberOf、@NotMemberOf
表达式或自定义
@Assert、@CheckWith、@NotMatchPatternCheck,@MatchPatternCheck、@ValidateWithMethod

4)使用

import net.sf.oval.ConstraintViolation;
import net.sf.oval.Validator;
import net.sf.oval.constraint.Length;
import net.sf.oval.constraint.Max;
import net.sf.oval.constraint.Min;

import java.util.List;

public class OvalTest {
    public static void main(String[] args) {
        Person p = new Person("test",1);
        Validator validator = new Validator();
        List<ConstraintViolation> validate = validator.validate(p);
        for (ConstraintViolation constraintViolation : validate) {
            System.out.println(constraintViolation.getMessage());
        }
    }
}

class Person{
    @Length(min = 6, max = 10)
    private String name;
    @Min(4)
    @Max(10)
    private Integer age;

    public Person(String name,Integer age){
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

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

2 Hibernate-validator
1)依赖

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

2)常用注解
@Null–被注释的元素必须是null
@NotNull–被注释的元素必须不为null
@AssertTrue–被注释的元素必须为true
@AssetFalse–被注释的元素必须为false
@Min(value)–被注释的元素必须为数字,且值大于等于指定的值
@Max(value)–被注释的元素必须为数字,且值小于等于指定的值
@DecimalMin(value)–被注释的元素必须为数字,且值大于等于指定的值
@DecimalMin(value)–被注释的元素必须为数字,且值小于等于指定的值
@Size(max,min)–被注释的元素的大小必须在指定的范围内
@Digits(integer,frcation)–被注释的元素必须是数字,其值必须在可接受的范围内
@Past–被注释的元素必须是一个过去的日期
@Future–被注释的元素必须是一个将来的日期
@Pattern(value)–被注释的元素必须符合正则表达式

3)使用

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.util.Set;
public class ValidationApiTest {
    public static void main(String[] args) {
        Person p = new Person("test",1);
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        Validator validator = factory.getValidator();
        Set<ConstraintViolation<Person>> validate = validator.validate(p);
        for (ConstraintViolation constraintViolation : validate) {
            System.out.println(constraintViolation.getMessage());
        }
    }
}

class Person{
    @NotNull
    private String name;
    @Min(4)
    @Max(10)
    private Integer age;

    public Person(String name,Integer age){
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

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

配合SpringMVC使用
mvc:annotation-driven/会默认装配好一个LocalValidatorFactoryBean,通过在处理方法的入参上标注@Valid注解既可让Spring MVC在完成数据绑定后执行数据校验的工作

public class User {   
      @Pattern(regexp="w{4,30}")
      private String userName;
	
      @Length(min=2,max=100)
      private String realName;
	
     @Past 
     @DateTimeFormat(pattern="yyyy-MM-dd")
     private Date birthday;
	
    @DecimalMin(value="1000.00")
    @DecimalMax(value="100000.00") 
    @NumberFormat(pattern="#,###.##")
    private long salary;
}

@Controller
public class UserController {
     @RequestMapping(value = "/handle91")
     public String handle91(@Valid  User user,BindingResult bindingResult){		
          if(bindingResult.hasErrors()){
               return "/user/register3";
          }else{
               return "/user/showUser";
          }
    }

4)自定义注解参见:https://www.cnblogs.com/softidea/p/9712571.html

 类似资料: