码迷,mamicode.com
首页 > Web开发 > 详细

hibernate validator工具类

时间:2017-06-05 19:26:26      阅读:371      评论:0      收藏:0      [点我收藏+]

标签:ext   write   配置   const   java   artifact   工具类   stat   for   

一、相关的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工具类

标签:ext   write   配置   const   java   artifact   工具类   stat   for   

原文地址:http://www.cnblogs.com/yoyotl/p/6946618.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!