基于配置文件进行接口字段的校验
这是自己的一个小总结与分析。
按公司架构师的要求,接口要实现基于配置文件进行接口字段的校验,好处能保证报文完整性,而且业务有新需求,只需要改配置文件,是一种很好的思想。
配置文件如下:
<Config> <in> <Student isnull="false" /> <Teacher isnull="ture" defaultType="cons" defaultValue="tom"> <Math isnull="ture" defaultType="func" class="com..." mathod="add" > </in> <out></out> </Config>
config对应的是我的接口业务名,in是输入字段,里面定义了三种类型,一种只要判断是否为空, 另一种是如果为空,就要给默认值,有是常量的,有要通过函数得值的。大家可以自己根据自己的需求定义。
然后定义了静态的解析xml的类。
public class ConfigurationFileAnalyze { public static List<Element> configurationAnalyze (String xmlName){ String path="/"+xmlName; SAXBuilder builder = new SAXBuilder(); Document doc = null; doc=builder.build(path); elements =doc.getRootElements("Congfig"); return elements; }
public static List<Element> getElements (String xmlName){
return configurationAnalyze (String xmlName);
} }
接下来是我的接口实现类(去除了抛出异常日志记录,只有具体的解析xml和校验):
public class XmlDiverService{
private List<Element> elements;
public HashMap<String,Object> qutaInfo(HashMap<String,Object> hashMap){
elements = ConfigurationFileAnalyze.getElements(""DeriService.xml);
HashMap<String,Object> repMap= new HashMap<String,Object>() ;
for (int i=0; i<elements.size(); i++) {
if (hashMap.get("PriceType").equals(elements.get(i).getAttributeValue("value"))){
Element rec = elements.get(i);
Element in = rec.getChild("in");
List <Element> list = in.getChildren();
for (Map.Entry<String,String> entry: hashMap.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
for (Element element : list){
//配置文件节点与传入参数匹配
if (element.getName().equals(key)) {
//如果匹配子节点的isnull属性值是false则是必输字段
if ("false".equals(element.getAttributeValue("isnull"))){
if (isNullorEmpty(value)) {
repMap.put("error","");
return repMap;
}
}
//不是必输字段,需要赋默认值的字段
else{
//字段是常量值直接赋值
if ("cons".equals(element.getAttributeValue("defaultType")){
if (isNullorEmpty(value)) {
entry.setValue(element.getAttributeValue("defaultValue"));
}
}else {
//是函数得值
String name = element.getAttributeValue("class");
Stirng method = element.getAttributeValue("method");
Class c = Class.forName(name);
Method m = c.getDeclaredMethod(method , new Class[]{String.class,Stirng.class}) ;
value = m.invoke(obj,new Object[]{hashMap.get("cc1"),hashMap.get("cc2")}).toString;
entry.setValue(value);
}
}
}
}
}
}
}

浙公网安备 33010602011771号