JSP基于dom解析xml实例详解

 更新时间:2015年11月05日 12:35:05   作者:awj3584  
这篇文章主要介绍了JSP基于dom解析xml的方法,以完整实例形式较为详细的分析了JSP使用dom针对xml文件解析的相关技巧,具有一定参考借鉴价值,需要的朋友可以参考下

本文实例讲述了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程序设计有所帮助。

相关文章

最新评论