用户注册登录注销
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语法 Listlist=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(); //创建 元素 Element userElement=DocumentHelper.createElement("user"); userElement.setAttributeValue("username", user.getUsername()); userElement.setAttributeValue("password", user.getPassword()); //挂载到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>