目录
1.什么是XML建模
2.XML建模过程
2.1 思路:
1.分析层级结构
2.分析XML文件中的对象和属性
3.通过23种的设计模式中的工厂模式,解析xml生产的对象
2.2 代码实现:
(1).封装好层级对象
下面都是get,set方法,需要注意的是, 一定要根据XML文件中的属性写,但出现对象时,用Map集合进行表示
例:
<config> <action path="/regAction" type="test.RegAction"> <forward name="failed" path="/reg.jsp" redirect="false" /> <forward name="success" path="/login.jsp" redirect="true" /> </action> <action path="/loginAction" type="test.LoginAction"> <forward name="failed" path="/login.jsp" redirect="false" /> <forward name="success" path="/main.jsp" redirect="true" /> </action> </config>
由代码中我们可以看出,action在config中,当我们在写ConfigModel的时候可以将ActionModel当做对象用map集合存储
以上面的XML文件为例,需要将先将forward放到action中,再将action放到config中
(2)工厂模式
package com.YU.model; import java.io.InputStream; import java.util.List; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; /** * * @author 21879 * 23种设计模式之工厂模式--创建型模式 */ public class ConfigModelFatory { public static ConfigModel bulid() throws Exception { ConfigModel configmodel = new ConfigModel(); //加载xml文件 InputStream in = ConfigModelFatory.class.getResourceAsStream("config.xml"); SAXReader sr = new SAXReader(); Document doc = sr.read(in); List<Element> actionEles = doc.selectNodes("/config/action"); for (Element actionEle : actionEles) { //实例化actionModel对象 ActionModel actionModel = new ActionModel(); //设置属性值 actionModel.setPath(actionEle.attributeValue("path")); actionModel.setType(actionEle.attributeValue("type")); //将forward属性设置好并放入actionModel中后再将actionModel放入configModel List<Element> forwardEles = actionEle.selectNodes("forward"); for (Element forwardEle : forwardEles) { //实例化forwardModel对象 ForwardModel forwardModel = new ForwardModel(); //设置属性值 forwardModel.setName(forwardEle.attributeValue("name")); forwardModel.setPath(forwardEle.attributeValue("path")); //只有填写false才是转发,其他都是重定向 forwardModel.setRedirect(!"false".equals(forwardEle.attributeValue("redirect"))); //将forwardModel放入actionModel actionModel.push(forwardModel); } configmodel.push(actionModel); } return configmodel; } public static void main(String[] args) throws Exception { ConfigModel configmodel = ConfigModelFatory.bulid(); ActionModel actionModel = configmodel.pop("/loginAction"); ForwardModel forwardModel = actionModel.pop("success"); System.out.println(forwardModel.getPath()); } }
代码中都有相应的注释,理解好思路,结合代码
3.总结:
1.清楚XML建模的思路
2.层级嵌套
3.存储和获取内容的方式
3.1 push(压栈)
//将forward放进action中(压栈) public void push(ForwardModel formodel) { fmap.put(formodel.getName(), formodel); }
3.2 pop(弹栈)
//根据name属性将forward从action中取出(弹栈) public ForwardModel pop(String name) { return fmap.get(name); }