1. 程式人生 > >hibernate validator工具類

hibernate validator工具類

else get date sub store setresult sys fault pen

一、相關的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;

hibernate validator工具類