主頁 > 知識庫 > JSP基于dom解析xml實例詳解

JSP基于dom解析xml實例詳解

熱門標簽:百度地圖添加標注圖標樣式 地圖標注市場怎么樣 南京新思維電話機器人 聊城智能電銷機器人外呼 好操作的電話機器人廠家 企業(yè)怎么在聯(lián)通申請400電話 如何用中國地圖標注數(shù)字點 南昌市地圖標注app 泰州泰興400電話 怎么申請

本文實例講述了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;
 }
}

數(shù)據(jù)訪問層接口:UserDao

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

接口實現(xiàn)類:UserDaoImpl

public class UserDaoImpl implements UserDao {
 private static final String PATH="xml文件路徑";
 private void build(Document dom) {
 try {
  //定義轉(zhuǎn)換器
  Transformer f = TransformerFactory.newInstance().newTransformer();
  //設(shè)置輸出的編碼格式
  f.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
  //構(gòu)建dom源
  DOMSource source = new DOMSource(dom);
  //指定文件存放的目標路勁
  StreamResult sr = new StreamResult(new File(PATH));
  //執(zhí)行轉(zhuǎn)換操作
  f.transform(source, sr);
 } catch (Exception e) {
  e.printStackTrace();
 }
 }
 //登陸
 public boolean login(String name, String pwd) {
 boolean flag = false;
 try {
  //根據(jù)以有的xml文件創(chuàng)建Document對象
  Document dom = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File(PATH));
  //獲取user節(jié)點下的子節(jié)點
  NodeList list = dom.getElementsByTagName("user");
  //遍歷list,數(shù)據(jù)匹配退出
  for(int i = 0; ilist.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 {
  //創(chuàng)建全新的Document對象
  Document dom = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
  //創(chuàng)建根節(jié)點users
  Element el = dom.createElement("users");
  //將根節(jié)點添加到dom中
  dom.appendChild(el);
  //創(chuàng)建子節(jié)點
  Element e2 = dom.createElement("user");
  //將子節(jié)點添加到根節(jié)點中
  el.appendChild(e2);
  //取得xml文件中現(xiàn)有的信息
  ListUser> users = this.selectUser();
  for(int i = 0; i  users.size(); i++){
  //創(chuàng)建節(jié)點user
  Element el3 = dom.createElement("user");
  User us =users.get(i);
  //設(shè)置節(jié)點的屬性(name,pwd,email)
  el3.setAttribute("name", us.getName());
  el3.setAttribute("pwd", us.getPwd());
  el3.setAttribute("email", us.getEmail());
  //添加到根節(jié)點中
  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 ListUser> selectUser() {
 ListUser> userList = new ArrayListUser>();
 try {
  //根據(jù)已有的xml文件創(chuàng)建dom
  Document dom = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File(PATH));
  //獲取所有user節(jié)點下的子節(jié)點
  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 {
  //根據(jù)以有的xml文件創(chuàng)建dom
  Document dom = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File(PATH));
  //獲取user節(jié)點下的子節(jié)點
  NodeList list = dom.getElementsByTagName("user");
  //遍歷list
  for(int i = 0;i  list.getLength();i++) {
  Element el = (Element)list.item(i);
  //根據(jù)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 {
  //根據(jù)以有xml文件創(chuàng)建domcumet對象
  Document dom = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File(PATH));
  //獲取user節(jié)點下的子節(jié)點
  NodeList list = dom.getElementsByTagName("user");
  //遍歷list
  for(int i=0;ilist.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;
 }
 //根據(jù)name查找
 public User findByName(String name) {
 User user = new User();
 try {
  //根據(jù)以后的xml文件創(chuàng)建document對象
  Document dom = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File(PATH));
  //獲取user節(jié)點下的子節(jié)點集合
  NodeList list = dom.getElementsByTagName("user");
  for(int i=0;ilist.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;
 }
}

業(yè)務(wù)邏輯層接口:UserService

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

接口實現(xiàn)類: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 ListUser> 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();
 ListUser> users = new ArrayListUser>();
 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程序設(shè)計有所幫助。

您可能感興趣的文章:
  • JavaScript和HTML DOM的區(qū)別與聯(lián)系及Javascript和DOM的關(guān)系
  • JavaScript對HTML DOM使用EventListener進行操作
  • JavaScript簡單遍歷DOM對象所有屬性的實現(xiàn)方法
  • 詳解javascript跨瀏覽器事件處理程序
  • JavaScript實現(xiàn)為指定對象添加多個事件處理程序的方法
  • 輕松創(chuàng)建nodejs服務(wù)器(5):事件處理程序
  • JS注冊/移除事件處理程序(ExtJS應用程序設(shè)計實戰(zhàn))
  • 淺談Javascript事件處理程序的幾種方式
  • js使用函數(shù)綁定技術(shù)改變事件處理程序的作用域
  • JavaScript事件處理程序(事件偵聽器)
  • JavaScript Event學習第三章 早期的事件處理程序
  • JavaScript將DOM事件處理程序封裝為event.js 出現(xiàn)的低級錯誤問題

標簽:開封 白銀 自貢 山南 銅川 吉林 烏蘭察布 臨汾

巨人網(wǎng)絡(luò)通訊聲明:本文標題《JSP基于dom解析xml實例詳解》,本文關(guān)鍵詞  JSP,基于,dom,解析,xml,實例,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 下面列出與本文章《JSP基于dom解析xml實例詳解》相關(guān)的同類信息!
  • 本頁收集關(guān)于JSP基于dom解析xml實例詳解的相關(guān)信息資訊供網(wǎng)民參考!
  • 推薦文章