CODY

CODY 关注TA

一坑未平,一坑起

CODY

CODY

关注TA

一坑未平,一坑起

  •  深圳南山
  • java酱油党
  • 写了59,448字

最近回复

该文章投稿至Nemo社区   Java  板块 复制链接


验证前端传参某些值是必输的

发布于 2017/02/10 09:41 1,490浏览 2回复 1,712

场景:当新增一个对象时,但是某些值是必输项,这时需要验证参数不能为空,否则保存不成功

案例:

1.验证WithdrawalIouManagementFee的calcType,borrowMainTakeCharge,guaranteeMainTakeCharge为必输项

public void checkIouManagementFeeField(WithdrawalIouManagementFee managementFees) throws LambdaServiceException {
        
        String[][] sourceArr = {{"calcType","管理费计算方式编码"},{"borrowMainTakeCharge","管理费借款主体承担"},{"guaranteeMainTakeCharge","管理费担保主体承担"}};

        checkFeild(managementFees,sourceArr,WithdrawalIouManagementFee.class);
    }

2. 利用java反射,得到getter()方法,取得对应的值,再判断是否null,并返回对应的提示

private void checkFeild(Object obj,String [][] sourceArr,Class cls) throws LambdaServiceException{
        String desc = null;
        try{
           for (int i = 0; i < sourceArr.length; i++) {
               String fields[] = sourceArr[i];
               String key = fields[0];
               
               //key --> getKey 
               
               if(key!=null && key.length()>0){
                   String getter = "get" + key.substring(0,1).toUpperCase() + key.substring(1,key.length());
                   Method method = cls.getMethod(getter, null);
                   Object value = method.invoke(obj, null);
                   if(value == null || value.toString().trim().equals("")){      //value is null , throw 
                       desc = fields[1];//备注
                       throw new LambdaServiceException();
                   }
               }
               
           }
        }catch (LambdaServiceException e){
            throw new LambdaServiceException(desc + "不能为空!");
        }catch (Exception e){
            log.debug("信息校验异常>>>>>>>>>>>>",e);
        }
    }
点赞(0)

上一个文章:git 的部分常用命令

点了个评