使用oVal进行Java Bean 验证的注意事项

如果需要不同条件验证不同的属性的时候,需要使用profiles属性,每个校验注解符中都有。注意:oVal默认是启用所有的profiles,所以在对单独一个profile进行启用的时候,需要先disableAllProfiles

当使用除了@NotNull之外的校验符时,需使用@NotNull先校验,否则其他校验符不起作用。譬如当使用@ValidateWithMethod校验符的时候,需要先使用@NotNull进行校验

全部Bean properties代码如下:

@Data
public class NewHouseInputParam {

    @NotNull(errorCode = "-10001", message = "orderId不能为空")
    private Long orderId;// 订单Id
    @NotNull(errorCode = "-1", message = "INPUT订单状态不能为空")
    private Integer status; //(1,"录入报备",""),(2,"录入到访",""),(3,"录入无效",""),(4,"录入下定",""),(5,"录入成交",""),(6,"录入开票",""),(7,"录入结佣",""),

    //报备录入
    @NotNull(profiles = {"profile_1"},errorCode = "-1", message = "报备日期不能为空")
    @ValidateWithMethod(profiles = {"profile_1"},methodName = "isValidDate",parameterType = String.class,
            errorCode = "-1", message = "报备日期不合法")
    private String applyDate;// 报备日期

    //到访录入
    @NotNull(profiles = {"profile_2"},errorCode = "-1", message = "到访日期不能为空")
    @ValidateWithMethod(profiles = {"profile_2"},methodName = "isValidDate",parameterType = String.class,
            errorCode = "-1", message = "到访日期不合法")
    private String visitDate;// 到访日期
    @NotNull(profiles = {"profile_2"},errorCode = "-1", message = "到访确认单照片不能为空")
    private String visitImgKey;// 到访确认单照片

    //下定录入
    @NotNull(profiles = {"profile_4"},errorCode = "-1", message = "下定合同照片不能为空")
    private String bookImgKey;// 下定合同照片
    @NotNull(profiles = {"profile_4"},errorCode = "-1", message = "产品id不能为空")
    private Long bookProductId;// 产品id
    @NotNull(profiles = {"profile_4"},errorCode = "-1", message = "下定合同编号不能为空")
    @MaxLength(value = 20,profiles = {"profile_4"},errorCode = "-1", message = "下定合同编号不合法")
    private String bookContractCode;// 下定合同编号

    @NotNull(profiles = "profile_4",errorCode = "-1", message = "下定金额不能为空")
    @ValidateWithMethod(profiles = {"profile_4"},methodName = "isValid6Money",parameterType = String.class,
            errorCode = "-1", message = "下定金额不合法")
    private String bookPrice;// 下定金额
    @NotNull(profiles = "profile_4",errorCode = "-1", message = "购房总价不能为空")
    @ValidateWithMethod(profiles = {"profile_4"},methodName = "isValid9Money",parameterType = String.class,
            errorCode = "-1", message = "购房总价不合法")
    private String bookTotalPrice;// 购房总价
    @NotNull(profiles = "profile_4",errorCode = "-1", message = "预计佣金不能为空")
    @ValidateWithMethod(profiles = {"profile_4"},methodName = "isValid9Money",parameterType = String.class,
            errorCode = "-1", message = "预计佣金不合法")
    private String bookPossibleCommission;// 预计佣金
    @NotNull(profiles = "profile_4",errorCode = "-1", message = "下定日期不能为空")
    @ValidateWithMethod(profiles = {"profile_4"},methodName = "isValidDate",parameterType = String.class,
            errorCode = "-1", message = "下定日期不合法")
    private String bookDate;// 下定日期

    //成交录入
    @NotNull(profiles = {"profile_5"},errorCode = "-1", message = "合同照片不能为空")
    @MinLength(profiles = "profile_5",value = 1,errorCode = "-1",message = "合同照片不能为空")
    private String dealImgKey;// 合同照片
    @NotNull(profiles = {"profile_5"},errorCode = "-1", message = "合同总价不能为空")
    @ValidateWithMethod(profiles = {"profile_5"},methodName = "isValid6Money",parameterType = String.class,
            errorCode = "-1", message = "合同总价不合法")
    private String dealContractPrice;// 合同总价
    @NotNull(profiles = {"profile_5"},errorCode = "-1", message = "产品Id不能为空")
    private Long dealProductId;// 产品Id
    @NotNull(profiles = {"profile_5"},errorCode = "-1", message = "合同编号不能为空")
    @MinLength(profiles = "profile_5",value = 1,errorCode = "-1",message = "合同编号不能为空")
    private String dealContractCode;// 合同编号
    @NotNull(profiles = {"profile_5"},errorCode = "-1", message = "应收佣金不能为空")
    @ValidateWithMethod(profiles = {"profile_5"},methodName = "isValid6Money",parameterType = String.class,
            errorCode = "-1", message = "应收佣金不合法")
    private String dealReceivableCommission;// 应收佣金
    @NotNull(profiles = {"profile_5"},errorCode = "-1", message = "成交日期不能为空")
    @ValidateWithMethod(profiles = {"profile_5"},methodName = "isValidDate",parameterType = String.class,
            errorCode = "-1", message = "成交日期不合法")
    private String dealDate;// 成交日期
    @NotNull(profiles = {"profile_5"},errorCode = "-1", message = "室不能为空")
    @Range(profiles = {"profile_5"},min = 0,max = 9,errorCode = "-1", message = "室不合法")
    private Integer bedroomSum;// 室
    @NotNull(profiles = {"profile_5"},errorCode = "-1", message = "厅不能为空")
    @Range(profiles = {"profile_5"},min = 0,max = 9,errorCode = "-1", message = "厅不合法")
    private Integer livingRoomSum;// 厅
    @NotNull(profiles = {"profile_5"},errorCode = "-1", message = "卫不能为空")
    @Range(profiles = {"profile_5"},min = 0,max = 9,errorCode = "-1", message = "卫不合法")
    private Integer wcSum;// 卫
    @NotNull(profiles = {"profile_5"},errorCode = "-1", message = "面积不能为空")
    @ValidateWithMethod(profiles = {"profile_5"},methodName = "isValid4Money",parameterType = String.class,
            errorCode = "-1", message = "面积不合法")
    private String spaceArea;// 面积
    @NotNull(profiles = {"profile_5"},errorCode = "-1", message = "室号不能为空")
    @MaxLength(profiles = {"profile_5"},value = 10,errorCode = "-1", message = "室号非法")
    private String room;// 室号
    @NotNull(profiles = {"profile_5"},errorCode = "-1", message = "楼栋号不能为空")
    @MaxLength(profiles = {"profile_5"},value = 10,errorCode = "-1", message = "楼栋号非法")
    private String building;// 楼栋号

    //开票录入
    @NotNull(profiles = {"profile_6"},errorCode = "-1", message = "开票金额不能为空")
    @ValidateWithMethod(profiles = {"profile_6"},methodName = "isValid6Money",parameterType = String.class,
            errorCode = "-1", message = "开票金额不合法")
    private String invoicePrice;// 开票金额
    @NotNull(profiles = {"profile_6"},errorCode = "-1", message = "开票日期不能为空")
    @ValidateWithMethod(profiles = {"profile_6"},methodName = "isValidDate",parameterType = String.class,
            errorCode = "-1", message = "开票日期不合法")
    private String invoiceDate;// 开票日期

    //结佣录入
    @NotNull(profiles = {"profile_7"},errorCode = "-1", message = "结佣金额不能为空")
    @ValidateWithMethod(profiles = {"profile_7"},methodName = "isValid6Money",parameterType = String.class,
            errorCode = "-1", message = "结佣金额不合法")
    private String commissionPrice;// 结佣金额
    @NotNull(profiles = {"profile_7"},errorCode = "-1", message = "结佣日期不能为空")
    @ValidateWithMethod(profiles = {"profile_7"},methodName = "isValidDate",parameterType = String.class,
            errorCode = "-1", message = "结佣日期不合法")
    private String commissionDate;// 结佣日期

    //失效录入
    @NotNull(profiles = {"profile_3"},errorCode = "-1", message = "失效原因不能为空")
    @MaxLength(profiles = {"profile_3"},value = 100,errorCode = "-1", message = "失效原因不合法")
    private String invalidDesc;// 失效原因

    @Override
    public String toString() {
        return "NewHouseInputParam{" +
                "orderId=" + orderId +
                ", status=" + status +
                ", applyDate=‘" + applyDate + ‘\‘‘ +
                ", visitDate=‘" + visitDate + ‘\‘‘ +
                ", visitImgKey=‘" + visitImgKey + ‘\‘‘ +
                ", bookImgKey=‘" + bookImgKey + ‘\‘‘ +
                ", bookProductId=" + bookProductId +
                ", bookContractCode=‘" + bookContractCode + ‘\‘‘ +
                ", bookPrice=" + bookPrice +
                ", bookTotalPrice=" + bookTotalPrice +
                ", bookPossibleCommission=" + bookPossibleCommission +
                ", bookDate=‘" + bookDate + ‘\‘‘ +
                ", dealImgKey=‘" + dealImgKey + ‘\‘‘ +
                ", dealContractPrice=" + dealContractPrice +
                ", dealProductId=" + dealProductId +
                ", dealContractCode=" + dealContractCode +
                ", dealReceivableCommission=" + dealReceivableCommission +
                ", dealDate=‘" + dealDate + ‘\‘‘ +
                ", bedroomSum=" + bedroomSum +
                ", livingRoomSum=" + livingRoomSum +
                ", wcSum=" + wcSum +
                ", spaceArea=‘" + spaceArea + ‘\‘‘ +
                ", room=‘" + room + ‘\‘‘ +
                ", building=‘" + building + ‘\‘‘ +
                ", invoicePrice=‘" + invoicePrice + ‘\‘‘ +
                ", invoiceDate=‘" + invoiceDate + ‘\‘‘ +
                ", commissionPrice=‘" + commissionPrice + ‘\‘‘ +
                ", commissionDate=‘" + commissionDate + ‘\‘‘ +
                ", invalidDesc=‘" + invalidDesc + ‘\‘‘ +
                ‘}‘;
    }

    /**
     * 验证日期格式是否合法
     * @param date
     * @return
     */
    public boolean isValidDate(String date){
        Date d = DateUtil.stringToDate(date, "YYYY-MM-dd");
        return d != null;
    }

    /**
     * 验证范围{0.00-9999.99}
     * @param money
     * @return
     */
    private boolean isValid4Money(String money){
        money = numericalMax2Points(money);
        if(money != null){
            float f = Float.parseFloat(money);
            if(f >= 0 && f < 10000){
                return true;
            }
        }
        return false;
    }

    /**
     * 验证范围{0.00-999999.99}
     * @param money
     * @return
     */
    private boolean isValid6Money(String money){
        money = numericalMax2Points(money);
        if(money != null){
            float f = Float.parseFloat(money);
            if(f >= 0 && f < 1000000){
                return true;
            }
        }
        return false;
    }

    /**
     * 验证范围{0.00-999,999,999.99}
     * @param money
     * @return
     */
    private boolean isValid9Money(String money){
        money = numericalMax2Points(money);
        if(money != null){
            float f = Float.parseFloat(money);
            if(f >= 0 && f < 1000000000){
                return true;
            }
        }
        return false;
    }

    /**
     * 判断在去除","后是否是数字,并且最多两位小数
     * 正确则返回处理后的money
     * 否则返回null
     * @param money
     * @return
     */
    private String numericalMax2Points(String money){
        try {
            if (money != null) {
                if (money.indexOf(",") > 0 || money.indexOf(",") > 0) {
                    money = StringUtil.remove(money, ‘,‘);
                    money = StringUtil.remove(money, ‘,‘);
                }
                if (money.matches("-?[0-9]+.?([0-9]{0,2})")) {
                    return money;
                }
            }
        }catch (Exception e){}
        return null;
    }
}
    使用oVal代码,自己封装的Response:
//验证参数是否正确
        WeixinEntValidatorUtil util = WeixinEntValidatorUtil.getInstance();
        util.disableAllProfiles();
        util.enableProfile("profile_" + param.getStatus());
        res = util.validate(param);
        if(res.getStatus() != null && res.getStatus() != 0){
            return res;
        }

WeixinEntValidatorUtil代码如下:

public class WeixinEntValidatorUtil extends ValidatorUtil<Response> {
    private static final WeixinEntValidatorUtil WEIXIN_ENT_VALIDATOR_UTILS = new WeixinEntValidatorUtil();

    public static WeixinEntValidatorUtil getInstance(){return WEIXIN_ENT_VALIDATOR_UTILS;}

    /**
     * 失败
     * @param errorCode
     * @param message
     * @return
     */
    @Override
    protected Response transferResponse(String errorCode, String message) {
        Integer errorCodeInt;
        try {
            errorCodeInt = Integer.parseInt(errorCode);
        }catch (Exception e) {
            errorCodeInt = -1;
        }
        return new Response(errorCodeInt,message);
    }

    /**
     * 成功
     * @param o
     * @return
     */
    @Override
    protected Response succResponse(Object o) {
        return new Response(0,"");
    }

    public Response validate(Object o){return getInstance()._validate(o);}

    @Override
    protected Response _validate(Object o) {
        return super._validate(o);
    }
}

父类代码:

public abstract class ValidatorUtil<T> {

    private static final Validator validator = new Validator();

    protected abstract T transferResponse(String errorCode,String message);

    protected abstract T succResponse(Object o);

    /**
     * if the object is null then the util by oval will throw exception
     * @param o
     * @return
     */
    protected T _validate (Object o) {
        List<ConstraintViolation> violations = validator.validate(o);
        if (violations.size() > 0) {
            //System.out.println(violations);
            return transferResponse(violations.get(0).getErrorCode(),violations.get(0).getMessage());
        }
        return succResponse(o);
    }

    public void disableProfile(String profileName){
        validator.disableProfile(profileName);
    }

    public void disableAllProfiles(){
        validator.disableAllProfiles();
    }

    public void enableProfile(String profileName){
        validator.enableProfile(profileName);
    }

    public void enableAllProfiles(){
        validator.enableAllProfiles();
    }

}
时间: 2024-10-13 16:19:20

使用oVal进行Java Bean 验证的注意事项的相关文章

Java参数验证Bean Validation 框架

1.为什么要做参数校验? 参数校验和业务逻辑代码分离,参数校验代码复用,统一参数校验方式.校验不太通过时统一异常描述. 2.bean validation规范 JSR303 规范(Bean Validation 规范)提供了对 Java EE 和 Java SE 中的 Java Bean 进行验证的方式.该规范主要使用注解的方式来实现对 Java Bean 的验证功能,并且这种方式会覆盖使用 XML 形式的验证描述符,从而使验证逻辑从业务代码中分离出来.JSR303注解如下: Hibernate

基于Java Bean Validation对Request参数进行校验的设计思路

摘自Hibernate Validator文档: 数据校验是任何一个应用程序都会用到的功能,无论是显示层还是持久层. 通常,相同的校验逻辑会分散在各个层中, 这样,不仅浪费了时间还会导致重复代码的发生. 为了避免重复, 开发人员经常会把这些校验逻辑直接写在领域模型里面, 但是这样又把领域模型代码和校验代码混杂在了一起, 而这些校验逻辑更应该是描述领域模型的元数据. JSR 303 - Bean Validation (version 1.1)- 为实体验证定义了元数据模型和API. 默认的元数据

java数据验证

数据验证在 Java 分层结构的应用开发中占据着重要位置.Java EE 6 提出了 Bean Validation 规范,使用注解的方式对 Java Bean 进行约束验证,不局限于某一层次或者某一编程模型,灵活易用 Bean Validation 规范 Bean 是 Java Bean 的缩写,在 Java 分层架构的实际应用中,从表示层到持久化层,每一层都需要对 Java Bean 进行业务符合性验证,如图 1 所示.然而对于同一个 Java Bean 的对象,在每一层都需要实现同样的验证

深入了解数据校验:Java Bean Validation 2.0(JSR380)

每篇一句 吾皇一日不退役,尔等都是臣子 相关阅读 [小家Java]深入了解数据校验(Bean Validation):基础类打点(ValidationProvider.ConstraintDescriptor.ConstraintValidator) 对Spring感兴趣可扫码加入wx群:`Java高工.架构师3群`(文末有二维码) 前言 前几篇文章在讲Spring的数据绑定的时候,多次提到过数据校验.可能有人认为数据校验模块并不是那么的重要,因为硬编码都可以做.若是这么想的话,那就大错特错了~

Java Bean

Java 帝国之Java bean (上) Java 帝国之Java bean(下) Difference between DTO, VO, POJO, JavaBeans? Java bean 是个什么概念? JavaBean的详细及引用

java 安全验证方法

输入数据验证:虽然为方便用户而在客户端层上提供数据验证,但仍必须使用 Servlet 在服务器层上执行数据验证.客户端验证本身就不安全,因为这 些验证可轻易绕过,例如,通过禁用 Javascript. 一份好的设计通常需要 Web 应用程序框架,以提供服务器端实用程序例程,从而验证以下内容:[1] 必需字段[2] 字段数据类型(缺省情况下,所有 HTTP 请求参数都是"字符串")[3] 字段长度[4] 字段范围[5] 字段选项[6] 字段模式[7] cookie 值[8] HTTP 响

如何快速通过json构建java bean对象

和第三方对接的时候,返回给我们的json时参数字段多是很常见的现象,所以我们手动去创建javabean肯定是要花费不少时间,可用通过json自动生成javabean的工具,这里简单的介绍一下Intellij IDEA 中的插件GsonFormat. 1.什么是GsonFormat 将json数据格式转换为java bean对象的as插件. 2.快捷键 Ctrl+ALT+S,或settings -->Plugins -->输入GsonFormat   install plugins 安装完成,重

spring mvc返回json字符串数据,只需要返回一个java bean对象就行,只要这个java bean 对象实现了序列化serializeable

1.spring mvc返回json数据,只需要返回一个java bean对象就行,只要这个java bean 对象实现了序列化serializeable 2. @RequestMapping(value = { "/actor_details" }, method = { RequestMethod.POST }) @ResponseBody public ResultObject actorDetails(@RequestBody ActorDetailsRequest req)

使用谷歌Gson实现Json串和Java Bean互转

/** * 使用谷歌Gson实现Json串和Java Bean互转 */ public class JsonHelper { public static String toJson(Object src){ return new Gson().toJson(src); } public static <T> T fromJson(String json, Class<T> clazz) throws Exception { return new Gson().fromJson(js