使用Digester解析XML文件和JAVA对象的映射

    技术2022-05-11  76

    package  cn.hxex.exam.config; import  java.util.Hashtable; import  cn.hxex.exam.exception.ExamException; public   class  ExamConfig  {   private Hashtable daos;   public ExamConfig(){       daos=new Hashtable();   }   public void addDao(DAOConfig bean){       daos.put(bean.getId(), bean);   }      public DAOConfig getDAOConfig(String name){       DAOConfig config=(DAOConfig)daos.get(name);       if(config==null){           throw new ExamException("couldn't find the bean:"+name);       }       return config;   }} package  cn.hxex.exam.config; import  java.io.InputStream; import  org.apache.commons.digester.Digester; public   class  ExamConfigUtil  {   public static final String DEFAULT_CONFIG_FILE="ExamConfig.xml";   public static final ExamConfig MESSAGE_CONFIG;      static{       Digester digester=new Digester();       digester.setValidating(false);              //初始化根配置对象       digester.addObjectCreate("config""cn.hxex.exam.config.Examconfig");       digester.addSetProperties("config");              //初始化DAOConfig对象       digester.addObjectCreate("config/daos/dao""cn.hxex.exam.config.DAOConfig");       digester.addSetProperties("config/daos/dao");       digester.addSetNext("config/dao/dao""addDao","cn.hxex.exam.config.DAOConfig");              //读取配置文件       ClassLoader classLoader=Thread.currentThread().getContextClassLoader();       InputStream in=classLoader.getResourceAsStream(DEFAULT_CONFIG_FILE);       ExamConfig config=null;       try {          if(in!=null){              config=(ExamConfig)digester.parse(in);          }        } catch (Exception e) {          e.printStackTrace();       }        MESSAGE_CONFIG=config;       }      public static ExamConfig getConfig(){       return ExamConfigUtil.MESSAGE_CONFIG;   }      public static DAOConfig getDAOConfig(String name){       return MESSAGE_CONFIG.getDAOConfig(name);   }   } < config >      < daos >          < dao  id ="UserDAO"  type ="cn.hxex.exam.dao.hibernate.UserDAOHibernate"   />          < dao  id ="TeacherDAO"  type ="cn.hxex.exam.dao.hibernate.TeacherDAOHibernate"   />          < dao  id ="TestPaperDAO"  type ="cn.hxex.exam.dao.hibernate.TestPaperDAOHibernate"   />          < dao  id ="RoleDAO"  type ="cn.hxex.exam.dao.hibernate.RoleDAOHibernate"   />          < dao  id ="ClassesDAO"  type ="cn.hxex.exam.dao.hibernate.ClassesDAOHibernate"   />          < dao  id ="StudentDAO"  type ="cn.hxex.exam.dao.hibernate.StudentDAOHibernate"   />          < dao  id ="SelectQuestionDAO"  type ="cn.hxex.exam.dao.hibernate.SelectQuestionDAOHibernate"   />          < dao  id ="YesNoQuestionDAO"  type ="cn.hxex.exam.dao.hibernate.YesNoQuestionDAOHibernate"   />      </ daos >      < cache  type ="cn.hxex.exam.cache.ehcache.EHCache" >          < property  name ="cachename"  value ="cache"   />      </ cache >      < sysconfig >          < property  name ="superuser"  value ="super,test"   />      </ sysconfig > </ config >

    最新回复(0)