JSP基於dom解析xml執行個體詳解_JSP編程

來源:互聯網
上載者:User

本文執行個體講述了JSP基於dom解析xml的方法。分享給大家供大家參考,具體如下:

初次學慣用dom操作xml檔案,有很多不足之處,牛人多給點建議,練習時我沒對中文做亂碼處理,也沒做驗證哦!O(∩_∩)O~

實體類:User

public class User { private String name; private String pwd; private String email; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; }}

資料訪問層介面:UserDao

public interface UserDao { boolean login(String name, String pwd); void insertUser(User user); List<User> selectUser(); void updateUser(User user); boolean deleteUser(String name); public User findByName(String name);}

介面實作類別:UserDaoImpl

public class UserDaoImpl implements UserDao { private static final String PATH="xml檔案路徑"; private void build(Document dom) { try {  //定義轉換器  Transformer f = TransformerFactory.newInstance().newTransformer();  //設定輸出的編碼格式  f.setOutputProperty(OutputKeys.ENCODING, "UTF-8");  //構建dom源  DOMSource source = new DOMSource(dom);  //指定檔案存放的目標路勁  StreamResult sr = new StreamResult(new File(PATH));  //執行轉換操作  f.transform(source, sr); } catch (Exception e) {  e.printStackTrace(); } } //登陸 public boolean login(String name, String pwd) { boolean flag = false; try {  //根據以有的xml檔案建立Document對象  Document dom = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File(PATH));  //擷取user節點下的子節點  NodeList list = dom.getElementsByTagName("user");  //遍曆list,資料匹配退出  for(int i = 0; i<list.getLength(); i++) {  Element el = (Element)list.item(i);  if(name.equals(el.getAttribute("name")) && pwd.equals(el.getAttribute("pwd"))) {   flag = true;   break;  }  } } catch (Exception e) {  // TODO Auto-generated catch block  e.printStackTrace(); }  return flag; } //添加操作 public void insertUser(User user) { try {  //建立全新的Document對象  Document dom = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();  //建立根節點users  Element el = dom.createElement("users");  //將根節點添加到dom中  dom.appendChild(el);  //建立子節點  Element e2 = dom.createElement("user");  //將子節點添加到根節點中  el.appendChild(e2);  //取得xml檔案中現有的資訊  List<User> users = this.selectUser();  for(int i = 0; i < users.size(); i++){  //建立節點user  Element el3 = dom.createElement("user");  User us =users.get(i);  //設定節點的屬性(name,pwd,email)  el3.setAttribute("name", us.getName());  el3.setAttribute("pwd", us.getPwd());  el3.setAttribute("email", us.getEmail());  //添加到根節點中  el.appendChild(el3);  }  e2.setAttribute("name", user.getName());  e2.setAttribute("pwd", user.getPwd());  e2.setAttribute("email", user.getEmail());  build(dom); } catch (ParserConfigurationException e) {  // TODO Auto-generated catch block  e.printStackTrace(); } } //查詢操作 public List<User> selectUser() { List<User> userList = new ArrayList<User>(); try {  //根據已有的xml檔案建立dom  Document dom = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File(PATH));  //擷取所有user節點下的子節點  NodeList list = dom.getElementsByTagName("user");  for(int i = 0;i <list.getLength();i++){  User user =new User();  Element element = (Element)list.item(i);  user.setName(element.getAttribute("name"));  user.setPwd(element.getAttribute("pwd"));  user.setEmail(element.getAttribute("email"));  userList.add(user);  } } catch (Exception e) {  // TODO Auto-generated catch block  e.printStackTrace(); } return userList; } //修改操作 public void updateUser(User user) { try {  //根據以有的xml檔案建立dom  Document dom = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File(PATH));  //擷取user節點下的子節點  NodeList list = dom.getElementsByTagName("user");  //遍曆list  for(int i = 0;i < list.getLength();i++) {  Element el = (Element)list.item(i);  //根據name屬性去修改  if(user.getName().equals(el.getAttribute("name"))) {   el.setAttribute("pwd", user.getPwd());   el.setAttribute("email", user.getEmail());   build(dom);  }  } } catch (SAXException e) {  // TODO Auto-generated catch block  e.printStackTrace(); } catch (IOException e) {  // TODO Auto-generated catch block  e.printStackTrace(); } catch (ParserConfigurationException e) {  // TODO Auto-generated catch block  e.printStackTrace(); } } //刪除操作 public boolean deleteUser(String name) { try {  //根據以有xml檔案建立domcumet對象  Document dom = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File(PATH));  //擷取user節點下的子節點  NodeList list = dom.getElementsByTagName("user");  //遍曆list  for(int i=0;i<list.getLength();i++) {  Element el = (Element)list.item(i);  if(name.equals(el.getAttribute("name"))) {   el.getParentNode().removeChild(el);   build(dom);   return true;  }  } } catch (Exception e) {  // TODO: handle exception } return false; } //根據name尋找 public User findByName(String name) { User user = new User(); try {  //根據以後的xml檔案建立document對象  Document dom = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File(PATH));  //擷取user節點下的子節點集合  NodeList list = dom.getElementsByTagName("user");  for(int i=0;i<list.getLength();i++) {  Element el = (Element)list.item(i);  if(name.equals(el.getAttribute("name"))) {   user.setName(el.getAttribute("name"));   user.setPwd(el.getAttribute("pwd"));   user.setEmail(el.getAttribute("email"));   break;  }  } } catch (Exception e) {  e.printStackTrace(); } return user; }}

商務邏輯層介面:UserService

boolean login(String name, String pwd);void insertUser(User user);List<User> selectUser();void updateUser(User user);boolean deleteUser(String name);public User findByName(String name);

介面實作類別:UserServiceImpl

public class UserServiceImpl implements UserService { UserDao dao = new UserDaoImpl(); public boolean login(String name, String pwd) { return dao.login(name, pwd); } public void insertUser(User user) { dao.insertUser(user); } public List<User> selectUser() { return dao.selectUser(); } public void updateUser(User user) { dao.updateUser(user); } public boolean deleteUser(String name) { return dao.deleteUser(name); } public User findByName(String name) { return dao.findByName(name); }}

控制層:UserAction

public class UserAction extends ActionSupport{  private User user; public User getUser() { return user; } public void setUser(User user) { this.user = user; } UserService userService = new UserServiceImpl(); public String selectUser(){ HttpServletRequest request = ServletActionContext.getRequest(); List<User> users = new ArrayList<User>(); users = userService.selectUser(); request.setAttribute("USER", users); return "select"; } /** * 登陸 * @return */ public String login(){ if(user.getName() != null && user.getPwd() != null) {  boolean flag = userService.login(user.getName(), user.getPwd());  if(flag) {  return SUCCESS;  } } return ERROR; } /** * 修改 * @return */ public String update(){ userService.updateUser(user); return "update"; } /** * 編輯 * @return */ public String edit(){ HttpServletRequest request = ServletActionContext.getRequest(); String name = request.getParameter("uName"); if(name != null) {  User u = userService.findByName(name);  request.setAttribute("USER", u); } return "edit"; } /** * 刪除 * @return */ public String delete(){ HttpServletRequest request = ServletActionContext.getRequest(); String name = request.getParameter("uName"); boolean flag = userService.deleteUser(name); System.out.println(flag); return SUCCESS; }  /**   * 添加   * @return   */ public String insert(){ userService.insertUser(user); return "insert"; }}

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

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC  "-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"  "http://struts.apache.org/dtds/struts-2.1.7.dtd"><struts>  <package name="file" extends="struts-default">   <action name="list" class="com.jun.action.UserAction" method="selectUser">    <result name="select">/list.jsp</result>   </action>   <action name="login" class="com.jun.action.UserAction" method="login">    <result name="success" type="redirectAction">/list.action</result>    <result name="error">/login.jsp</result>   </action>   <action name="insert" class="com.jun.action.UserAction" method="insert">    <result name="insert" type="redirectAction">/list.action</result>   </action>   <action name="delete" class="com.jun.action.UserAction" method="delete">    <result type="redirect">/list.action</result>     </action>   <action name="update" class="com.jun.action.UserAction" method="update">    <result name="update" type="redirectAction">/list.action</result>     </action>   <action name="edit" class="com.jun.action.UserAction" method="edit">    <result name="edit">/update.jsp</result>     </action>  </package></struts>

web.xml配置

<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5"  xmlns="http://java.sun.com/xml/ns/javaee"  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee  http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <welcome-file-list>  <welcome-file>index.jsp</welcome-file> </welcome-file-list> <filter>  <filter-name>struts2</filter-name>  <filter-class>  org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter  </filter-class> </filter> <filter-mapping>  <filter-name>struts2</filter-name>  <url-pattern>/*</url-pattern> </filter-mapping></web-app>

四個頁面:login.jsp  list.jsp insert.jsp,update.jsp

login.jsp

<%@ page language="java" import="java.util.*" pageEncoding="GBK"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head>  <base href="<%=basePath%>">  <title>My JSP 'login.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0">   <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body>  <a href="list.action">首頁</a>|<a href="insert.jsp">註冊</a>  <form action="login.action" method="post">  <table>  <tr>    <td> 使用者名稱:</td><td><input name="user.name" type="text"></td>  </tr>  <tr>    <td> 密碼:</td><td><input type="password" name="user.pwd"></td>  </tr>  <tr>    <td colspan="2" align="center"><input type="submit" value="登入"></td>  </tr>    </table>   </form> </body></html>

list.jsp

<%@ page language="java" import="java.util.*" pageEncoding="GBK"%><%@ taglib uri="/struts-tags" prefix="s"%><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head>  <base href="<%=basePath%>">  <title>My JSP 'list.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0">   <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body > <a href="insert.jsp">註冊</a>  <table border="1">  <tr>   <td align="center" colspan="6"><font size="+3">使用者列表</font></td>  </tr>   <tr>    <td>序號</td><td>使用者名稱</td><td>密碼</td><td>郵箱</td><td>刪除</td><td>編輯</td>   </tr>   <c:forEach items="${USER}" var="u" varStatus="temp">    <tr>    <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>    </tr>  </c:forEach>  </table> </body></html>

insert.jsp

<%@ page language="java" import="java.util.*" pageEncoding="GBK"%><% String path = request.getContextPath(); String basePath = request.getScheme() + "://"  + request.getServerName() + ":" + request.getServerPort()  + path + "/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <base href="<%=basePath%>"> <title>My JSP 'register.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <a href="list.action">首頁</a> <form action="insert.action" method="post">  <table>  <tr>   <td>   使用者名稱:   </td>   <td>   <input name="user.name" type="text">   </td>  </tr>  <tr>   <td>   密碼:   </td>   <td>   <input type="password" name="user.pwd">   </td>  </tr>  <tr>   <td>   郵箱:   </td>   <td>   <input type="text" name="user.email">   </td>  </tr>  <tr>   <td colspan="2" align="center">   <input type="submit" value="提交">   </td>  </tr>  </table> </form> </body></html>

update.jsp

<%@ page language="java" import="java.util.*" pageEncoding="GBK"%><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head>  <base href="<%=basePath%>">  <title>My JSP 'update.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0">   <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body>  <a href="list.action">首頁</a>  <h2>更新操作</h2>  <form action="update.action" method="post">  <table>  <c:set value="${USER}" var="user"></c:set>  <tr>    <td> 使用者名稱:</td><td><input readonly="readonly" name="user.name" value="${user.name}" type="text"></td>  </tr>  <tr>    <td> 密碼:</td><td><input type="password" value="${user.pwd }" name="user.pwd"></td>  </tr>  <tr>    <td> 郵箱:</td><td><input type="text" value="${user.email }" name="user.email"></td>  </tr>  <tr>    <td colspan="2" align="center"><input type="submit" value="儲存"></td>  </tr>    </table>   </form> </body></html>

本人學習所用的user.xml檔案

<?xml version="1.0" encoding="UTF-8"?><users><user email=aaa@sina.com name="bbb" pwd="aaaaaa"/><user email=bbb@sina.com name="ccc" pwd="aaaaaa"/></users>

希望本文所述對大家jsp程式設計有所協助。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.