maven validator数据校验

1、maven文件中添加依赖包

 
    
      org.hibernate
      hibernate-validator
      5.0.2.Final
    


 
         org.jboss.logging
         jboss-logging
         3.3.0.Final
     

 2、实体类文件中添加注解

package com.text;

import org.hibernate.validator.constraints.Email;

public class User {
   @Email
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    private String name;
    private int age;
}

  

3、在调用实体类之前输出校验结果

public User sayHello(@Valid User user, BindingResult result){
        //System.out.println(user.getName());

        if(result.getErrorCount()>0){
            System.out.println("出错了!");
            for(FieldError error:result.getFieldErrors()){
                System.out.println(error.getField()+":"+error.getDefaultMessage());
            }
            //如果验证出错,那么转向出错的页面
        }
        return  user;
    }

  

Bean Validation 中内置的 constrain
Hibernate Validator 附加的 constraint

转载于:https://www.cnblogs.com/cyrfr/p/9274194.html

你可能感兴趣的:(maven validator数据校验)