本文主要是介绍参数校验 验签,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
//service层
public class ApiServiceImpl{public Map<String,Object> query(DTO dto){Map<String,Object> result = new HashMap<String,Object>();result.put("resultCode",StatusCode.SUCCESS);result.put("resultMsg","查询成功");//参数校验(通常校验非空)Map<String,Object> checkParamsResult = checkParams(dto);if("F".equals(MapUtils.getString(checkParamsResult,"resultCode"))){result.put("resultCode",StatusCode.PARAMS_NULL);result.put("resultMsg",checkParamsResult.get("resultMsg"));return result;}//验签if(!checkSign(dto)){result.put("resultCode",StatusCode.SIGN_ERROR);result.put("resultMsg","验签失败");return result;}//业务代码//省略}}
//xx接口的校验参数
public Map<String,Object> checkParams(DTO dto){//添加需要校验的参数ValidatorList validatorList = new ValidatorList();validatorList.add(MapValidator.notEmpty("appId","appId不能为空"));validatorList.add(MapValidator.notEmpty("companyNo","companyNo不能为空"));validatorList.add(MapValidator.notEmpty("sign","sign不能为空"));validatorList.add(MapValidator.notEmpty("businessNo","businessNo不能为空"));//校验dtoreturn validatorList.validateToMapResult(transBean2Map(dto))
}
//Validator组合,支持多种validator
public ValidatorList implements Validator{private List validators = new ArrayList();public Map validateToMapResult(Object data){Errors errors = new Errors();validate(data,errors);Map result = new HashMap();result.put("resultCode","N");if(e.hasError()){Iterator it = e.iterator();StringBuffer sb = new StringBuffer();while(it.hasNext()){sb.append((it.next()).getMessage()).append(".");}result.put("resultCode","Y");result.put("resultMsg",sb.toString());}return result;}public void validate(Object data,Errors e){Errors temp = new Errors();Iterator it = validators.iterator();while(it.hasNext()){Validator v = it.next();//这里的validate,就是根据validator的类型,即service方法中ValidatorList里添加的validator,这里添加的是MapValidator.notEmpty("companyNo","companyNo不能为空"),说明require会返回一个validator。v.validate(data,temp);}//将temp里的内容装到e中e.add(temp);}
}
public abstract class MapValidator implements Validator{//校验非空public static MapValidator notEmpty(final String field,final String resultMsg){return new MapValueNotEmpty(field,resultMsg);}//校验日期格式public static MapValidator date(final String field,final String resultMsg,final String pattern){return new MapValueDateFormat(field,resultMsg,pattern);}//校验数字public static number(final String field,final String resultMsg){return new MapValueValidator(field,resultMsg){@Overrideprotected boolean validate(Object o){if(null == o){return true;}try{//如果能转换成功,则说明字符串是数字格式,程序能正常往下走,如果转换失败,则异常,走catch块。new BigDecimal((String)o);return true;}catch(Exception e){return false;}}}}
}
public class MapValueNotEmpty extends MapValueValidator{public void validate(Object o){return isEmpty(o)}
}
public abstract class MapValueValidator extends MapValidator{protected boolean isEmpty(Object o){if(null == o){return true;}if(!(o instance of String)){return false;}return ((String)o).trim().equals("");}}
这篇关于参数校验 验签的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!