Servlet+JSP+javaBean+dom4j
分层结构:
com.tsh.web
com.tsh.service
com.tsh.dao
com.tsh.domain
com.tsh.util
com.tsh.test
com.tsh.exception
com.tsh.factory
使用的包:
dom4j jstl beanutils junit
users.xml-----------模拟数据库
config.properties------------主配置文件
XPATH:
dom4j提供的方法,可以在xml文件中查找指定的节点,类似正则在文本文件中查找指定文本
com.tsh.dao.XmlUserDao.java
package com.tsh.dao; import java.util.List; org.dom4j.Document; org.dom4j.DocumentHelper; org.dom4j.Element; com.tsh.domain.User; com.tsh.util.XmlDaoUtil; public class XmlUserDao { /** * 根据用户名查找user * @param username * @return */ public User findUserByUsername(String username){ Document dom=XmlDaoUtil.getDom(); Element root=dom.getRootElement(); //使用XPATH语法 List<Element> list=root.selectNodes("//user[@username='"+username+"']"); if(list.size()>0){ Element userElement=list.get(0); String uname=userElement.attributeValue("username"); String password=userElement.attributeValue("password"); 将用户信息封装到bean User user=new User(); user.setUsername(uname); user.setPassword(password); user.setPassword_confirm(password); return user; } return null; } * 添加用户 * user void addUser(User user){ Document dom=创建<user>元素 Element userElement=DocumentHelper.createElement("user"); userElement.setAttributeValue("username",user.getUsername()); userElement.setAttributeValue("password"挂载到<users> root.add(userElement); 回写到xml文件 } }
com.tsh.util.XmlDaoUtil.java
com.tsh.util; java.net.URL; org.dom4j.io.SAXReader; XmlDaoUtil { private static URL path=XmlDaoUtil.class.getClassLoader().getResource("user.xml"); * 使用静态代码块,对象只实例化一次 static Document dom; { SAXReader reader= SAXReader(); try { 类加载器找到物理路径 dom=reader.read(path); } catch (Exception e) { e.printStackTrace(); } } * 获取xml * Document getDom(){ dom; } * 写入xml static writeXml(){ } }
com.tsh.domain.User.java
com.tsh.domain; java.io.Serializable; class User implements Serializable{ private String username; String password; String password_confirm; String getUsername() { username; } setUsername(String username) { this.username = String getPassword() { password; } setPassword(String password) { this.password = String getPassword_confirm() { password_confirm; } setPassword_confirm(String password_confirm) { this.password_confirm = password_confirm; } }
user.xml
<?xml version="1.0" encoding="UTF-8"?> <users> user username="admin" password="admin"></user</>