package com.haha.action; import java.util.HashMap; import java.util.List; import java.util.Map; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.SAXReader; public class ActionFactory { private static Map<String, AbsMyStrutsAction> map=null; //初始化 private static void init(){ try { SAXReader sr = new SAXReader(); Document doc = sr.read(ActionFactory.class.getResource("/actions.xml")); List<Element> list=doc.selectNodes("/beans/bean"); for(Element el:list){ //获取name属性 String name=el.attributeValue("name"); //获取class属性 String clsName=el.attributeValue("class"); //创建一个Action对象 AbsMyStrutsAction action=createAction(clsName); if(action!=null){ map.put(name, action); } } } catch (Exception e) { e.printStackTrace(); } } //根据类名创建一个Action private static AbsMyStrutsAction createAction(String clsName) { try { Class cls = Class.forName(clsName); return (AbsMyStrutsAction) cls.newInstance(); } catch (Exception e) { e.printStackTrace(); return null; } } //根据名字获取一个Action public static AbsMyStrutsAction getAction(String name){ if(map==null){ map=new HashMap<String, AbsMyStrutsAction>(); init(); } if(map.containsKey(name)){ return map.get(name); } return null; } }