一、相关的gradle配置文件
// https://mvnrepository.com/artifact/javax.el/javax.el-api compile group: ‘javax.el‘, name: ‘javax.el-api‘, version: ‘3.0.0‘ // https://mvnrepository.com/artifact/org.glassfish.web/javax.el compile group: ‘org.glassfish.web‘, name: ‘javax.el‘, version: ‘2.2.6‘ // https://mvnrepository.com/artifact/org.hibernate/hibernate-validator compile group: ‘org.hibernate‘, name: ‘hibernate-validator‘, version: ‘5.4.1.Final‘
二、validate接口支持泛型参数
public static ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); public String validObject(Object msg) { String result = ConstantUtil.VALID_PASS; Validator validator = factory.getValidator(); Set<ConstraintViolation<Object>> constraintViolations = validator.validate(msg); if(constraintViolations.isEmpty()){ return result; } StringBuffer buff = new StringBuffer(); for (ConstraintViolation<Object> constraintViolation : constraintViolations) { buff.append(constraintViolation.getInvalidValue()); buff.append(":"); buff.append(constraintViolation.getMessage()); buff.append("!\n"); } return buff.toString().substring(0,buff.toString().length()-1); }
三、调用示例
public MsgBaseResponse processEmService(Emp em) { MsgBaseResponse response = new MsgBaseResponse(); String validResult = validUtil.validObject(em); if (validResult.equals(ConstantUtil.VALID_PASS)) { //TODO: the Operate and data. System.out.println("valid success, can write to store."); response.setData(""); } else { response.setResult(-1); response.setData(validResult); } return response;
时间: 2024-10-11 23:25:18