J2EE从入门到入土03 XML的解析&建模

目录

解析

解析XML的案例操作 

 XML建模步骤

环境的搭建 

建立相关的包及MVC的配置文件

 通过config.xml格式建立相关的模型类

自定义异常

观察MVC的配置文件config.xml来编写代码

模型类代码编写

 工厂类ConfigModelFactory编写

解析

解析XML需要的知识

类名.class.getResourceAsStream("xxx"):拿到同包下的文件

类名.class.getResourceAsStream("/xxx"):拿到根目录下的文件

context.getResourceAsStream("/WIN-INF/xxx"):拿到WIN-INF安全路径

dome4j jar包的基本方法 

selectNodes:拿到多个元素

selectSingleNode:拿到单个元素

getRootElement():拿到根元素

attributeValue:只有元素才可以点出这个方法来获取值

getText:拿到元素文本

注:元素可以是节点,但是元素中的属性是节点不是元素

xpath语法 

/:定位路径

@:属性

解析XML的案例操作 

 解析XML只要导入dome4j jar包

 解析的XML文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE config[
	<!ELEMENT config (action*)>
	<!ELEMENT action (forward*)>
	<!ELEMENT forward EMPTY>
	<!ATTLIST action
	  path CDATA #REQUIRED
	  type CDATA #REQUIRED
	>
	<!ATTLIST forward
	  name CDATA #REQUIRED
	  path CDATA #REQUIRED
	  redirect (true|false) "false"
	>
]>
<config>
	<action path="/studentAction" type="org.lisen.mvc.action.StudentAction">
		<forward name="students" path="/students/studentList.jsp" redirect="false"/>
	</action>
	<action path="/studentAction02" type="org.lisen.mvc.action.StudentAction">
		<forward name="students02" path="/students/studentList.jsp" redirect="false"/>
	</action>
</config>

 编写解析操作的代码

public class XmlReader {
	
	public static void main(String[] args) throws Exception {
		InputStream in = XmlReader.class.getResourceAsStream("/config.xml");//获取XML的文件内容
		SAXReader reader = new SAXReader();//读取XML的内容
		Document doc = reader.read(in);//获得一个对象
 
		Element rootElement = doc.getRootElement();//获得对象里面的元素
		List<Element> actions = rootElement.selectNodes("action");//根据名字查询到多个元素
		
		for(Element e:  actions) {//遍历元素集合
			String path = e.attributeValue("path");//拿到对应元素节点下的元素内容
			String type = e.attributeValue("type");//拿到对应元素节点下的元素内容
			
			System.out.println("action path = "+path);
			System.out.println("action type = "+type);
			
			List<Element> forwards = e.selectNodes("forward");
			for(Element f:  forwards) {
				String name = f.attributeValue("name");
				String fPath = f.attributeValue("path");
				String redirect = f.attributeValue("redirect");
				
				System.out.println("forward name = "+name);
				System.out.println("forward fPath = "+fPath);
				System.out.println("forward redirect = "+redirect);
			}
			System.out.println("已结束解析");
		}
	}
}

 XML建模步骤

环境的搭建 

选择一个工作空间后点击Launch 

 点击首先选项来设置字符编码、部署环境及jdk工具包

 Workspace选项设置utf-8字符编码

 还有jsp files文件编码格式utf-8

 设置完成之后新建web 动态项目添加部署环境和jdk工具包,选择部署的tomcat点击next下一步

点击 Insetalled 选择安装的jdk版本

 

点击add添加   选择Standard VM点击下一步 选择jdk版本

 

 点击 Finish 就可以完成的  因为博主这里已经添加好了所以点不了

选择即可完成 ,还有一个jre自带的 我就删除了,不删也可以 

 选择jdk即可完成配置

一直点击下一步下一步到这里勾上Generate web.xml就可以完成了 

 导入以后需要的jar包

建立相关的包及MVC的配置文件

包名规范:com/org.公司名.项目名.模块名

  1. com.xyf.mvc.framework:框架包
  2. resources源码包下的文件:放自定义MVC的配置文件config.xml
  • config.xml代码展示👇(编写后续包、类、代码的依据!)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE config>
<config>
<action type="org.lisen.mvc.action.StudentAction" path="/studentAction">
<forward path="/students/studentList.jsp" redirect="false" name="students"/>
</action>
</config>

 通过config.xml格式建立相关的模型类

类名规范:首字母大写的驼峰命名法

模型类命名:

  • ConfigModel:Config节点模型
  • ActionModel:Action节点模型
  • ForwardModel:Farword节点模型

自定义异常

异常类命名+代码编写(关键是异常名称)

  • ActionDuplicateDefinitionException:Action元素中存在重复定义异常
public class ActionDuplicateDefinitionException extends RuntimeException {	
	public ActionDuplicateDefinitionException() {
		super();
	}	
	public ActionDuplicateDefinitionException(String msg) {
		super(msg);
	}	
	public ActionDuplicateDefinitionException(String msg, Throwable c) {
		super(msg, c);
	}
}
  • ActionNotFoundException:
public class ActionNotFoundException extends RuntimeException {	
	public ActionNotFoundException() {
		super();
	}	
	public ActionNotFoundException(String msg) {
		super(msg);
	}	
	public ActionNotFoundException(String msg, Throwable c) {
		super(msg, c);
	}
}
  •  ForwardDuplicateDefinitionException:Forward元素中存在重复定义异常
public class ForwardDuplicateDefinitionException extends RuntimeException {	
	public ForwardDuplicateDefinitionException() {
		super();
	}	
	public ForwardDuplicateDefinitionException(String msg) {
		super(msg);
	}	
	public ForwardDuplicateDefinitionException(String msg, Throwable c) {
		super(msg, c);
	}
}
  •  ForwardNotFoundException:
public class ForwardNotFoundException extends RuntimeException {	
	public ForwardNotFoundException() {
		super();
	}
	public ForwardNotFoundException(String msg) {
		super(msg);
	}	
	public ForwardNotFoundException(String msg, Throwable c) {
		super(msg, c);
	}
}

观察MVC的配置文件config.xml来编写代码

观察config.xml可知👇

  • 一个config节点下可以有多个action节点
  • action节点中具有type和path两个属性
  • action节点中有forward节点
  • forward节点具有三个属性......

模型类代码编写

根节点ConfigModel类

public class ConfigModel {
	
//	一个config节点下可以有多个action节点
//	放key==path和value==ActionModel类/对象:通过根节点找到action
//	初始化:new HashMap<>()
	private Map<String, ActionModel> actionMap=new HashMap<>();
	
	/**
	 * 将path放入key,保持path不重复
	 * 遍历ActionModel对象,通过ActionModel对象获取path属性
	 * @param 传入ActionModel这个类/对象
	 */
    public void put(ActionModel action) {
    	if(actionMap.containsKey(action.getPath())) {
    		throw new ActionDuplicateDefinitionException("Action path= "+action.getPath()+" Duplicate definition");
    	}
    	actionMap.put(action.getPath(), action);
    }
    
    /**
     * 找path
     * @param 传入path
     * @return 找不到path则抛出异常,找到就返回path
     */
    public ActionModel find(String path) {
    	if(!actionMap.containsKey(path)) {
    		throw new ActionNotFoundException("Action path ="+path+" not found");
    	}
    	return actionMap.get(path);
    }
    
}

ActionModel类

public class ActionModel {
	
//	有两个节点
	private String type;
	private String path;
	
//	包含元素forward:通过action找到forward
	private Map<String, ForwardModel> forwardMap =new HashMap<>();
	
//	将name放入key,保持name不重复
	public void put(ForwardModel forward) {
		if(forwardMap.containsKey(forward.getName())) {
			throw new ForwardDuplicateDefinitionException("forward name = "+forward.getName()+" DuplicateDefinition");
		}
		forwardMap.put(forward.getName(), forward);
	}
	
//	找name
	public ForwardModel find(String name) {
		if(!forwardMap.containsKey(name)) {
			throw new ForwardNotFoundException("forward name ="+name+" not found");
		}
		return forwardMap.get(name);
	}
	
	public String getType() {
		return type;
	}
	public void setType(String type) {
		this.type = type;
	}
	public String getPath() {
		return path;
	}
	public void setPath(String path) {
		this.path = path;
	}
 
	@Override
	public String toString() {
		return "ActionModel [type=" + type + ", path=" + path + ", forwardMap=" + forwardMap + "]";
	}	
}

 ForwardModel类

public class ForwardModel extends RuntimeException{
	//三个属性
	private String name;
	private String path;
	private boolean redirect;
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPath() {
		return path;
	}
	public void setPath(String path) {
		this.path = path;
	}
	public boolean isRedirect() {
		return redirect;
	}
	public void setRedirect(boolean redirect) {
		this.redirect = redirect;
	}
	
	//将redirect中的字符串转成boolean类型的方法
	public void setRedirect(String redirect) {
		//this=当前类
		this.redirect =Boolean.valueOf(redirect);
	}
	
	@Override
	public String toString() {
		return "ForwardModel [name=" + name + ", path=" + path + ", redirect=" + redirect + "]";
	}	
}

 工厂类ConfigModelFactory编写

编写工厂类ConfigModelFactory的目的是在这个类中使用单例模式,并且只对XML文件中的内容读取一次,读取后放入上一步编写好了的模型对象中

/**
 * 单例工厂类
 * 让解析XML的代码只执行一次
 */
@SuppressWarnings("unchecked")
public final class ConfigModelFactory {
	//单例模式
	private ConfigModelFactory() {}
	//根节点模型
	private static ConfigModel config = new ConfigModel();
	//只读取一次config中的数据,并填充到模型中
	static {
		try {
		//读
		InputStream is=XmlReader.class.getResourceAsStream("/config.xml");
		SAXReader reader=new SAXReader();
		
		Document doc = reader.read(is);
		//通过根元素获得根元素下的节点action(xml中的数结构!)
		Element rootElement = doc.getRootElement();
		List<Element> actions = rootElement.selectNodes("action");
		
		for (Element e : actions) {
			String path = e.attributeValue("path");
			String type = e.attributeValue("type");
			
			//放入模型
			ActionModel action=new ActionModel();
			action.setPath(path);
			action.setType(type);
			
			//通过action元素获得actions下面的节点forward
			List<Element> forward1 = e.selectNodes("forward");
			for (Element f : forward1) {
				String name = f.attributeValue("name");
				String fPath = f.attributeValue("path");
				String redirect = f.attributeValue("redirect");
				
				//放入模型
				ForwardModel forward=new ForwardModel();
				forward.setName(name);
				forward.setPath(fPath);
				forward.setRedirect(redirect);
				//将forward放入action
				action.put(forward);
				}
			//循环完成后将action放入根节点
			config.put(action);
			}
		} catch (DocumentException e) {
			e.printStackTrace();
		}
	}
	
	public static ConfigModel getConfig() {
		return config;
	}
	
    //测试
	public static void main(String[] args) {
		ConfigModel config = ConfigModelFactory.getConfig();
		//通过action中的path(xml中有/)找action
		ActionModel action = config.find("/studentAction");
		System.out.println(action);
		//通过forward中的name找forward,xml中无/
		ForwardModel forward = action.find("students");
		System.out.println(forward);
	}
	
}

本期内容到此就结束了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值