一.XML建模
封装:
以面向对象的方式去操作,封装对象
1.ConfigModel:
2.ActionModel:
3.ForwardModel:
二.工厂模式
将XML的内容初始化到描述出的模型对象中
这会报一个空指针异常的错误;
改成这样即可:
输出结果:
1.ConfigModelFactory:
package com.xiaoye.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;
public class ConfigModelFactory {
public static ConfigModel build() throws Exception {
ConfigModel configModel=new ConfigModel();
//得到一个流对象
InputStream in = ConfigModelFactory.class.getResourceAsStream("/mvc.xml");
//读取
SAXReader sr=new SAXReader();
Document d = sr.read(in);
// System.out.println(d.asXML());
//configModel要有内容,就意味这actionModel,然后放入configModel中。
List<Element> actionEles = d.selectNodes("/config/action");
for (Element actionEle : actionEles) {
// System.out.println(actionEle.asXML());
ActionModel actionModel=new ActionModel();
actionModel.setPath(actionEle.attributeValue("path"));
actionModel.setType(actionEle.attributeValue("type"));
//actionModel要有forwardModel,就意味这forwardModel,然后放入actionModel中。
List<Element> forwardEles = actionEle.selectNodes("forward");
for (Element forwardEle : forwardEles) {
System.out.println(forwardEle.asXML());
ForwardModel forwardModel=new ForwardModel();
forwardModel.setName(forwardEle.attributeValue("name"));
forwardModel.setPath(forwardEle.attributeValue("path"));
//只有填false才是转发,其他都是重定向
forwardModel.setRedirect(!"false".equals(forwardEle.attributeValue("redirect")));
actionModel.push(forwardModel);
}
//压榨
configModel.push(actionModel);
}
return configModel;
}
public static void main(String[] args) throws Exception {
ConfigModelFactory.build();
}
}
输出结果: