1、在Java包类创建一个class类实现Validator,重写supports和validate方法
EmpValidate.java
import com.qfedu.bean.Emp;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
/**
* Created by sun on 2020/3/5.
*/
public class EmpValidate implements Validator {
@Override
public boolean supports(Class<?> clazz) {
return Emp.class.isAssignableFrom(clazz);
}
@Override
public void validate(Object target, Errors errors) {
Emp e = (Emp) target;
ValidationUtils.rejectIfEmpty(errors, "eid", "emp.eid");
ValidationUtils.rejectIfEmpty(errors, "name", "emp.name");
ValidationUtils.rejectIfEmpty(errors, "salary", "emp.salary");
double salary = e.getSalary();
if(salary < 0){
errors.rejectValue("salary", "emp.salary.invalidate");
}
}
}
2、在webapp/WEBINF/下创建properties文件,文件命名为msg.properties,在里面存储校验错误信息的键值对。
emp.eid=eid不能为空.
emp.name=name不能为空
emp.salary=salary不能为空.
emp.salary.invalidate=salary不能为负数.