用戶注冊登錄注銷
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; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import com.tsh.domain.User; import 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; } /** * 添加用戶 * @param user */ public void addUser(User user){ Document dom=XmlDaoUtil.getDom(); Element root=dom.getRootElement(); //創建<user>元素 Element userElement=DocumentHelper.createElement("user"); userElement.setAttributeValue("username", user.getUsername()); userElement.setAttributeValue("password", user.getPassword()); //掛載到<users> root.add(userElement); //回寫到xml文件 } }
com.tsh.util.XmlDaoUtil.java
package com.tsh.util; import java.net.URL; import org.dom4j.Document; import org.dom4j.io.SAXReader; public class XmlDaoUtil { private static URL path=XmlDaoUtil.class.getClassLoader().getResource("user.xml"); /** * 使用靜態代碼塊,對象只實例化一次 */ private static Document dom; static{ SAXReader reader=new SAXReader(); try { //類加載器找到物理路徑 dom=reader.read(path); } catch (Exception e) { e.printStackTrace(); } } /** * 獲取xml * @return */ public static Document getDom(){ return dom; } /** * 寫入xml */ public static void writeXml(){ } }
com.tsh.domain.User.java
package com.tsh.domain; import java.io.Serializable; public class User implements Serializable{ private String username; private String password; private String password_confirm; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getPassword_confirm() { return password_confirm; } public void 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> </users>