使用javax的validation和hibernate-validator框架对pojo类的属性进行校验以及扩展

背景:如果页面表单有很多字段需要提交,因此使用注解校验的方式针对pojo的属性进行校验 因此使用javax标准以及org.hibernate的validator的注解校验

具体的javax的validation的注解以及hibernate的注解都是可以使用的,具体的扩展可以在网上找找,目前在这里就不再进行扩展了。一开始项目使用spring-module 0.9的jar,发现这个鬼东西不支持sprig4,spring4竟然不向下兼容。如果有用这个的可以考虑换成hibernate的注解校验

具体的实现,如下

package validation;

public class BizException extends RuntimeException {

    private String errorCode;

    private String errorMsg;

    public BizException(String errorCode, String errorMsg) {
        this.errorCode = errorCode;
        this.errorMsg = errorMsg;
    }

    public BizException(String message, String errorCode, String errorMsg) {
        super(message);
        this.errorCode = errorCode;
        this.errorMsg = errorMsg;
    }

    public BizException(String message, Throwable cause, String errorCode, String errorMsg) {
        super(message, cause);
        this.errorCode = errorCode;
        this.errorMsg = errorMsg;
    }

    public BizException(Throwable cause, String errorCode, String errorMsg) {
        super(cause);
        this.errorCode = errorCode;
        this.errorMsg = errorMsg;
    }

    public BizException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace, String errorCode, String errorMsg) {
        super(message, cause, enableSuppression, writableStackTrace);
        this.errorCode = errorCode;
        this.errorMsg = errorMsg;
    }

    public String getErrorCode() {
        return errorCode;
    }

    public void setErrorCode(String errorCode) {
        this.errorCode = errorCode;
    }

    public String getErrorMsg() {
        return errorMsg;
    }

    public void setErrorMsg(String errorMsg) {
        this.errorMsg = errorMsg;
    }
}
package validation;

public enum ErrorCodeEnum {
    ILLEGAL_PARAM("ILLEGAL_PARAM","服务正忙,请稍后再来");
    ;

    private String errorCode;

    private String errorMsg;


    ErrorCodeEnum(String errorCode, String errorMsg) {
        this.errorCode = errorCode;
        this.errorMsg = errorMsg;
    }

    public ErrorCodeEnum getErrorCode(String errorCode){
        for(ErrorCodeEnum code:values()){
            if(code.getErrorCode().equals(errorCode)){
                return code;
            }
        }
        return null;
    }
    public String getErrorCode() {
        return errorCode;
    }

    public void setErrorCode(String errorCode) {
        this.errorCode = errorCode;
    }

    public String getErrorMsg() {
        return errorMsg;
    }

    public void setErrorMsg(String errorMsg) {
        this.errorMsg = errorMsg;
    }
}
package validation;


import org.springframework.util.CollectionUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Iterator;
import java.util.Set;

public class ValidatorUtil {

    private static final Validator validator= Validation.buildDefaultValidatorFactory().getValidator();

    public static <T> String validate(T object){
        Set<ConstraintViolation<T>> violationSet=validator.validate(object);
        if(violationSet!=null&&!CollectionUtils.isEmpty(violationSet)){
            Iterator<ConstraintViolation<T>> iterator=violationSet.iterator();
            StringBuffer sb=new StringBuffer(64);
            while(iterator.hasNext()){
                sb.append(iterator.next().getMessage()).append(";");
            }
            return sb.toString();
        }
        return null;
    }
}
package validation;

public interface ValidatorWrapper {

    public void validate(Object object);
}
package validation;

import org.springframework.util.StringUtils;

public class ValidatorWrapperImpl implements ValidatorWrapper  {
    @Override
    public void validate(Object object) {
     if(object==null){
         throw new RuntimeException();
     }
     String msg=ValidatorUtil.validate(object);
     if(!StringUtils.isEmpty(msg)){
         throw new BizException(ErrorCodeEnum.ILLEGAL_PARAM.getErrorCode(),ErrorCodeEnum.ILLEGAL_PARAM.getErrorMsg());
     }
    }
}
package validation.shopdetail;


import org.hibernate.validator.constraints.NotBlank;

import javax.validation.constraints.NotNull;

public class ShopInfo {

    @NotNull(message="shopid不能为空")
    private String shopId;

    @NotBlank(message="shopName不能为空")
    private String shopName;


    private String telphone;


    public String getShopId() {
        return shopId;
    }

    public void setShopId(String shopId) {
        this.shopId = shopId;
    }

    public String getShopName() {
        return shopName;
    }

    public void setShopName(String shopName) {
        this.shopName = shopName;
    }

    public String getTelphone() {
        return telphone;
    }

    public void setTelphone(String telphone) {
        this.telphone = telphone;
    }
}
package validation.shopdetail;

import validation.BizException;
import validation.ValidatorWrapper;
import validation.ValidatorWrapperImpl;

public class ShopDeatilTest {

    public static void main(String[] args){

        ShopInfo shopInfo=new ShopInfo();
        shopInfo.setShopId("112");
        ValidatorWrapper validatorWrapper=new ValidatorWrapperImpl();
        try{
            validatorWrapper.validate(shopInfo);
        }catch (BizException e){
            System.out.println(e.getErrorCode()+"--"+e.getErrorMsg());
        }

    }

}

 

Hibernate Validator 是一个开源的校验框架,它实现了 JSR 380(Bean Validation 2.0)规范,提供了非常方便的校验工具。 以下是一个使用 Hibernate Validator 实现校验的工具示例: ```java import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; import java.util.Set; public class ValidationUtil { private static Validator validator = Validation.buildDefaultValidatorFactory().getValidator(); /** * 校验对象 * * @param obj 待校验对象 * @return 校验结果 */ public static <T> ValidationResult validateEntity(T obj) { ValidationResult result = new ValidationResult(); Set<ConstraintViolation<T>> set = validator.validate(obj); if (!set.isEmpty()) { result.setHasErrors(true); for (ConstraintViolation<T> cv : set) { result.getErrorMsgMap().put(cv.getPropertyPath().toString(), cv.getMessage()); } } return result; } } public class ValidationResult { private boolean hasErrors; private Map<String, String> errorMsgMap; public boolean isHasErrors() { return hasErrors; } public void setHasErrors(boolean hasErrors) { this.hasErrors = hasErrors; } public Map<String, String> getErrorMsgMap() { return errorMsgMap; } public void setErrorMsgMap(Map<String, String> errorMsgMap) { this.errorMsgMap = errorMsgMap; } } ``` 在上述代码中,我们使用 Hibernate Validator 提供的 `Validator` 实例,通过传入需要校验的对象,进行校验,并将校验结果封装到 `ValidationResult` 中返回。 使用时,只需要调用 `ValidationUtil.validateEntity(obj)` 方法即可。如果校验结果中 `hasErrors` 为 `true`,则说明校验未通过,具体错误信息可以通过 `errorMsgMap` 获取。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值