查看: 179|回复: 0

[Java学习] JSP基于dom解析xml实例详解

发表于 2016-6-8 08:05:38
游戏辅助AD

本文实例讲述了JSP基于dom解析xml的方法。分享给大家供大家参考,具体如下:

初次学习用dom操作xml文件,有很多不足之处,牛人多给点建议,练习时我没对中文做乱码处理,也没做验证哦!O(∩_∩)O~

实体类:User

  1. public class User {
  2. private String name;
  3. private String pwd;
  4. private String email;
  5. public String getName() {
  6. return name;
  7. }
  8. public void setName(String name) {
  9. this.name = name;
  10. }
  11. public String getPwd() {
  12. return pwd;
  13. }
  14. public void setPwd(String pwd) {
  15. this.pwd = pwd;
  16. }
  17. public String getEmail() {
  18. return email;
  19. }
  20. public void setEmail(String email) {
  21. this.email = email;
  22. }
  23. }
复制代码

数据访问层接口:UserDao

  1. public interface UserDao {
  2. boolean login(String name, String pwd);
  3. void insertUser(User user);
  4. List<User> selectUser();
  5. void updateUser(User user);
  6. boolean deleteUser(String name);
  7. public User findByName(String name);
  8. }
复制代码

接口实现类:UserDaoImpl

  1. public class UserDaoImpl implements UserDao {
  2. private static final String PATH="xml文件路径";
  3. private void build(Document dom) {
  4. try {
  5. //定义转换器
  6. Transformer f = TransformerFactory.newInstance().newTransformer();
  7. //设置输出的编码格式
  8. f.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
  9. //构建dom源
  10. DOMSource source = new DOMSource(dom);
  11. //指定文件存放的目标路劲
  12. StreamResult sr = new StreamResult(new File(PATH));
  13. //执行转换操作
  14. f.transform(source, sr);
  15. } catch (Exception e) {
  16. e.printStackTrace();
  17. }
  18. }
  19. //登陆
  20. public boolean login(String name, String pwd) {
  21. boolean flag = false;
  22. try {
  23. //根据以有的xml文件创建Document对象
  24. Document dom = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File(PATH));
  25. //获取user节点下的子节点
  26. NodeList list = dom.getElementsByTagName("user");
  27. //遍历list,数据匹配退出
  28. for(int i = 0; i<list.getLength(); i++) {
  29. Element el = (Element)list.item(i);
  30. if(name.equals(el.getAttribute("name")) && pwd.equals(el.getAttribute("pwd"))) {
  31. flag = true;
  32. break;
  33. }
  34. }
  35. } catch (Exception e) {
  36. // TODO Auto-generated catch block
  37. e.printStackTrace();
  38. }
  39. return flag;
  40. }
  41. //添加操作
  42. public void insertUser(User user) {
  43. try {
  44. //创建全新的Document对象
  45. Document dom = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
  46. //创建根节点users
  47. Element el = dom.createElement("users");
  48. //将根节点添加到dom中
  49. dom.appendChild(el);
  50. //创建子节点
  51. Element e2 = dom.createElement("user");
  52. //将子节点添加到根节点中
  53. el.appendChild(e2);
  54. //取得xml文件中现有的信息
  55. List<User> users = this.selectUser();
  56. for(int i = 0; i < users.size(); i++){
  57. //创建节点user
  58. Element el3 = dom.createElement("user");
  59. User us =users.get(i);
  60. //设置节点的属性(name,pwd,email)
  61. el3.setAttribute("name", us.getName());
  62. el3.setAttribute("pwd", us.getPwd());
  63. el3.setAttribute("email", us.getEmail());
  64. //添加到根节点中
  65. el.appendChild(el3);
  66. }
  67. e2.setAttribute("name", user.getName());
  68. e2.setAttribute("pwd", user.getPwd());
  69. e2.setAttribute("email", user.getEmail());
  70. build(dom);
  71. } catch (ParserConfigurationException e) {
  72. // TODO Auto-generated catch block
  73. e.printStackTrace();
  74. }
  75. }
  76. //查询操作
  77. public List<User> selectUser() {
  78. List<User> userList = new ArrayList<User>();
  79. try {
  80. //根据已有的xml文件创建dom
  81. Document dom = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File(PATH));
  82. //获取所有user节点下的子节点
  83. NodeList list = dom.getElementsByTagName("user");
  84. for(int i = 0;i <list.getLength();i++){
  85. User user =new User();
  86. Element element = (Element)list.item(i);
  87. user.setName(element.getAttribute("name"));
  88. user.setPwd(element.getAttribute("pwd"));
  89. user.setEmail(element.getAttribute("email"));
  90. userList.add(user);
  91. }
  92. } catch (Exception e) {
  93. // TODO Auto-generated catch block
  94. e.printStackTrace();
  95. }
  96. return userList;
  97. }
  98. //修改操作
  99. public void updateUser(User user) {
  100. try {
  101. //根据以有的xml文件创建dom
  102. Document dom = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File(PATH));
  103. //获取user节点下的子节点
  104. NodeList list = dom.getElementsByTagName("user");
  105. //遍历list
  106. for(int i = 0;i < list.getLength();i++) {
  107. Element el = (Element)list.item(i);
  108. //根据name属性去修改
  109. if(user.getName().equals(el.getAttribute("name"))) {
  110. el.setAttribute("pwd", user.getPwd());
  111. el.setAttribute("email", user.getEmail());
  112. build(dom);
  113. }
  114. }
  115. } catch (SAXException e) {
  116. // TODO Auto-generated catch block
  117. e.printStackTrace();
  118. } catch (IOException e) {
  119. // TODO Auto-generated catch block
  120. e.printStackTrace();
  121. } catch (ParserConfigurationException e) {
  122. // TODO Auto-generated catch block
  123. e.printStackTrace();
  124. }
  125. }
  126. //删除操作
  127. public boolean deleteUser(String name) {
  128. try {
  129. //根据以有xml文件创建domcumet对象
  130. Document dom = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File(PATH));
  131. //获取user节点下的子节点
  132. NodeList list = dom.getElementsByTagName("user");
  133. //遍历list
  134. for(int i=0;i<list.getLength();i++) {
  135. Element el = (Element)list.item(i);
  136. if(name.equals(el.getAttribute("name"))) {
  137. el.getParentNode().removeChild(el);
  138. build(dom);
  139. return true;
  140. }
  141. }
  142. } catch (Exception e) {
  143. // TODO: handle exception
  144. }
  145. return false;
  146. }
  147. //根据name查找
  148. public User findByName(String name) {
  149. User user = new User();
  150. try {
  151. //根据以后的xml文件创建document对象
  152. Document dom = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File(PATH));
  153. //获取user节点下的子节点集合
  154. NodeList list = dom.getElementsByTagName("user");
  155. for(int i=0;i<list.getLength();i++) {
  156. Element el = (Element)list.item(i);
  157. if(name.equals(el.getAttribute("name"))) {
  158. user.setName(el.getAttribute("name"));
  159. user.setPwd(el.getAttribute("pwd"));
  160. user.setEmail(el.getAttribute("email"));
  161. break;
  162. }
  163. }
  164. } catch (Exception e) {
  165. e.printStackTrace();
  166. }
  167. return user;
  168. }
  169. }
复制代码

业务逻辑层接口:UserService

  1. boolean login(String name, String pwd);
  2. void insertUser(User user);
  3. List<User> selectUser();
  4. void updateUser(User user);
  5. boolean deleteUser(String name);
  6. public User findByName(String name);
复制代码

接口实现类:UserServiceImpl

  1. public class UserServiceImpl implements UserService {
  2. UserDao dao = new UserDaoImpl();
  3. public boolean login(String name, String pwd) {
  4. return dao.login(name, pwd);
  5. }
  6. public void insertUser(User user) {
  7. dao.insertUser(user);
  8. }
  9. public List<User> selectUser() {
  10. return dao.selectUser();
  11. }
  12. public void updateUser(User user) {
  13. dao.updateUser(user);
  14. }
  15. public boolean deleteUser(String name) {
  16. return dao.deleteUser(name);
  17. }
  18. public User findByName(String name) {
  19. return dao.findByName(name);
  20. }
  21. }
复制代码

控制层:UserAction

  1. public class UserAction extends ActionSupport{
  2. private User user;
  3. public User getUser() {
  4. return user;
  5. }
  6. public void setUser(User user) {
  7. this.user = user;
  8. }
  9. UserService userService = new UserServiceImpl();
  10. public String selectUser(){
  11. HttpServletRequest request = ServletActionContext.getRequest();
  12. List<User> users = new ArrayList<User>();
  13. users = userService.selectUser();
  14. request.setAttribute("USER", users);
  15. return "select";
  16. }
  17. /**
  18. * 登陆
  19. * @return
  20. */
  21. public String login(){
  22. if(user.getName() != null && user.getPwd() != null) {
  23. boolean flag = userService.login(user.getName(), user.getPwd());
  24. if(flag) {
  25. return SUCCESS;
  26. }
  27. }
  28. return ERROR;
  29. }
  30. /**
  31. * 修改
  32. * @return
  33. */
  34. public String update(){
  35. userService.updateUser(user);
  36. return "update";
  37. }
  38. /**
  39. * 编辑
  40. * @return
  41. */
  42. public String edit(){
  43. HttpServletRequest request = ServletActionContext.getRequest();
  44. String name = request.getParameter("uName");
  45. if(name != null) {
  46. User u = userService.findByName(name);
  47. request.setAttribute("USER", u);
  48. }
  49. return "edit";
  50. }
  51. /**
  52. * 删除
  53. * @return
  54. */
  55. public String delete(){
  56. HttpServletRequest request = ServletActionContext.getRequest();
  57. String name = request.getParameter("uName");
  58. boolean flag = userService.deleteUser(name);
  59. System.out.println(flag);
  60. return SUCCESS;
  61. }
  62. /**
  63. * 添加
  64. * @return
  65. */
  66. public String insert(){
  67. userService.insertUser(user);
  68. return "insert";
  69. }
  70. }
复制代码

struts.xml配置(本人用的的struts2):

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE struts PUBLIC
  3. "-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
  4. "http://struts.apache.org/dtds/struts-2.1.7.dtd">
  5. <struts>
  6. <package name="file" extends="struts-default">
  7. <action name="list" class="com.jun.action.UserAction" method="selectUser">
  8. <result name="select">/list.jsp</result>
  9. </action>
  10. <action name="login" class="com.jun.action.UserAction" method="login">
  11. <result name="success" type="redirectAction">/list.action</result>
  12. <result name="error">/login.jsp</result>
  13. </action>
  14. <action name="insert" class="com.jun.action.UserAction" method="insert">
  15. <result name="insert" type="redirectAction">/list.action</result>
  16. </action>
  17. <action name="delete" class="com.jun.action.UserAction" method="delete">
  18. <result type="redirect">/list.action</result>
  19. </action>
  20. <action name="update" class="com.jun.action.UserAction" method="update">
  21. <result name="update" type="redirectAction">/list.action</result>
  22. </action>
  23. <action name="edit" class="com.jun.action.UserAction" method="edit">
  24. <result name="edit">/update.jsp</result>
  25. </action>
  26. </package>
  27. </struts>
复制代码

web.xml配置

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app version="2.5"
  3. xmlns="http://java.sun.com/xml/ns/javaee"
  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
  6. http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  7. <welcome-file-list>
  8. <welcome-file>index.jsp</welcome-file>
  9. </welcome-file-list>
  10. <filter>
  11. <filter-name>struts2</filter-name>
  12. <filter-class>
  13. org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
  14. </filter-class>
  15. </filter>
  16. <filter-mapping>
  17. <filter-name>struts2</filter-name>
  18. <url-pattern>/*</url-pattern>
  19. </filter-mapping>
  20. </web-app>
复制代码

四个页面:login.jsp list.jsp insert.jsp,update.jsp

login.jsp

  1. <%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
  2. <%
  3. String path = request.getContextPath();
  4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
  5. %>
  6. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  7. <html>
  8. <head>
  9. <base href="<%=basePath%>">
  10. <title>My JSP 'login.jsp' starting page</title>
  11. <meta http-equiv="pragma" content="no-cache">
  12. <meta http-equiv="cache-control" content="no-cache">
  13. <meta http-equiv="expires" content="0">
  14. <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
  15. <meta http-equiv="description" content="This is my page">
  16. <!--
  17. <link rel="stylesheet" type="text/css" href="styles.css">
  18. -->
  19. </head>
  20. <body>
  21. <a href="list.action">首页</a>|<a href="insert.jsp">注册</a>
  22. <form action="login.action" method="post">
  23. <table>
  24. <tr>
  25. <td> 用户名:</td><td><input name="user.name" type="text"></td>
  26. </tr>
  27. <tr>
  28. <td> 密码:</td><td><input type="password" name="user.pwd"></td>
  29. </tr>
  30. <tr>
  31. <td colspan="2" align="center"><input type="submit" value="登录"></td>
  32. </tr>
  33. </table>
  34. </form>
  35. </body>
  36. </html>
复制代码

list.jsp

  1. <%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
  2. <%@ taglib uri="/struts-tags" prefix="s"%>
  3. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
  4. <%
  5. String path = request.getContextPath();
  6. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
  7. %>
  8. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  9. <html>
  10. <head>
  11. <base href="<%=basePath%>">
  12. <title>My JSP 'list.jsp' starting page</title>
  13. <meta http-equiv="pragma" content="no-cache">
  14. <meta http-equiv="cache-control" content="no-cache">
  15. <meta http-equiv="expires" content="0">
  16. <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
  17. <meta http-equiv="description" content="This is my page">
  18. <!--
  19. <link rel="stylesheet" type="text/css" href="styles.css">
  20. -->
  21. </head>
  22. <body >
  23. <a href="insert.jsp">注册</a>
  24. <table border="1">
  25. <tr>
  26. <td align="center" colspan="6"><font size="+3">用户列表</font></td>
  27. </tr>
  28. <tr>
  29. <td>序号</td><td>用户名</td><td>密码</td><td>邮箱</td><td>删除</td><td>编辑</td>
  30. </tr>
  31. <c:forEach items="${USER}" var="u" varStatus="temp">
  32. <tr>
  33. <td>${temp.index+1}</td><td>${u.name }</td><td>${u.pwd }</td><td>${u.email}</td><td><a href="delete.action?uName=${u.name}">删除</a></td><td><a href="edit.action?uName=${u.name }">编辑</a></td>
  34. </tr>
  35. </c:forEach>
  36. </table>
  37. </body>
  38. </html>
复制代码

insert.jsp

  1. <%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
  2. <%
  3. String path = request.getContextPath();
  4. String basePath = request.getScheme() + "://"
  5. + request.getServerName() + ":" + request.getServerPort()
  6. + path + "/";
  7. %>
  8. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  9. <html>
  10. <head>
  11. <base href="<%=basePath%>">
  12. <title>My JSP 'register.jsp' starting page</title>
  13. <meta http-equiv="pragma" content="no-cache">
  14. <meta http-equiv="cache-control" content="no-cache">
  15. <meta http-equiv="expires" content="0">
  16. <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
  17. <meta http-equiv="description" content="This is my page">
  18. <!--
  19. <link rel="stylesheet" type="text/css" href="styles.css">
  20. -->
  21. </head>
  22. <body>
  23. <a href="list.action">首页</a>
  24. <form action="insert.action" method="post">
  25. <table>
  26. <tr>
  27. <td>
  28. 用户名:
  29. </td>
  30. <td>
  31. <input name="user.name" type="text">
  32. </td>
  33. </tr>
  34. <tr>
  35. <td>
  36. 密码:
  37. </td>
  38. <td>
  39. <input type="password" name="user.pwd">
  40. </td>
  41. </tr>
  42. <tr>
  43. <td>
  44. 邮箱:
  45. </td>
  46. <td>
  47. <input type="text" name="user.email">
  48. </td>
  49. </tr>
  50. <tr>
  51. <td colspan="2" align="center">
  52. <input type="submit" value="提交">
  53. </td>
  54. </tr>
  55. </table>
  56. </form>
  57. </body>
  58. </html>
复制代码

update.jsp

  1. <%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
  2. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
  3. <%
  4. String path = request.getContextPath();
  5. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
  6. %>
  7. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  8. <html>
  9. <head>
  10. <base href="<%=basePath%>">
  11. <title>My JSP 'update.jsp' starting page</title>
  12. <meta http-equiv="pragma" content="no-cache">
  13. <meta http-equiv="cache-control" content="no-cache">
  14. <meta http-equiv="expires" content="0">
  15. <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
  16. <meta http-equiv="description" content="This is my page">
  17. <!--
  18. <link rel="stylesheet" type="text/css" href="styles.css">
  19. -->
  20. </head>
  21. <body>
  22. <a href="list.action">首页</a>
  23. <h2>更新操作</h2>
  24. <form action="update.action" method="post">
  25. <table>
  26. <c:set value="${USER}" var="user"></c:set>
  27. <tr>
  28. <td> 用户名:</td><td><input readonly="readonly" name="user.name" value="${user.name}" type="text"></td>
  29. </tr>
  30. <tr>
  31. <td> 密码:</td><td><input type="password" value="${user.pwd }" name="user.pwd"></td>
  32. </tr>
  33. <tr>
  34. <td> 邮箱:</td><td><input type="text" value="${user.email }" name="user.email"></td>
  35. </tr>
  36. <tr>
  37. <td colspan="2" align="center"><input type="submit" value="保存"></td>
  38. </tr>
  39. </table>
  40. </form>
  41. </body>
  42. </html>
复制代码

本人学习所用的user.xml文件

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <users>
  3. <user email=aaa@sina.com name="bbb" pwd="aaaaaa"/>
  4. <user email=bbb@sina.com name="ccc" pwd="aaaaaa"/>
  5. </users>
复制代码

希望本文所述对大家jsp程序设计有所帮助。



回复

使用道具 举报