本文实例讲述了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):
<"1.0" encoding="UTF-8" "-//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配置
<"1.0" encoding="UTF-8""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">删除</a></td><td><a href="edit.action">编辑</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文件
<"1.0" encoding="UTF-8""bbb" pwd="aaaaaa"/> <user email=bbb@sina.com name="ccc" pwd="aaaaaa"/> </users>
希望本文所述对大家jsp程序设计有所帮助。
JSP,dom,解析xml
《魔兽世界》大逃杀!60人新游玩模式《强袭风暴》3月21日上线
暴雪近日发布了《魔兽世界》10.2.6 更新内容,新游玩模式《强袭风暴》即将于3月21 日在亚服上线,届时玩家将前往阿拉希高地展开一场 60 人大逃杀对战。
艾泽拉斯的冒险者已经征服了艾泽拉斯的大地及遥远的彼岸。他们在对抗世界上最致命的敌人时展现出过人的手腕,并且成功阻止终结宇宙等级的威胁。当他们在为即将于《魔兽世界》资料片《地心之战》中来袭的萨拉塔斯势力做战斗准备时,他们还需要在熟悉的阿拉希高地面对一个全新的敌人──那就是彼此。在《巨龙崛起》10.2.6 更新的《强袭风暴》中,玩家将会进入一个全新的海盗主题大逃杀式限时活动,其中包含极高的风险和史诗级的奖励。
《强袭风暴》不是普通的战场,作为一个独立于主游戏之外的活动,玩家可以用大逃杀的风格来体验《魔兽世界》,不分职业、不分装备(除了你在赛局中捡到的),光是技巧和战略的强弱之分就能决定出谁才是能坚持到最后的赢家。本次活动将会开放单人和双人模式,玩家在加入海盗主题的预赛大厅区域前,可以从强袭风暴角色画面新增好友。游玩游戏将可以累计名望轨迹,《巨龙崛起》和《魔兽世界:巫妖王之怒 经典版》的玩家都可以获得奖励。
更新动态
- 小骆驼-《草原狼2(蓝光CD)》[原抓WAV+CUE]
- 群星《欢迎来到我身边 电影原声专辑》[320K/MP3][105.02MB]
- 群星《欢迎来到我身边 电影原声专辑》[FLAC/分轨][480.9MB]
- 雷婷《梦里蓝天HQⅡ》 2023头版限量编号低速原抓[WAV+CUE][463M]
- 群星《2024好听新歌42》AI调整音效【WAV分轨】
- 王思雨-《思念陪着鸿雁飞》WAV
- 王思雨《喜马拉雅HQ》头版限量编号[WAV+CUE]
- 李健《无时无刻》[WAV+CUE][590M]
- 陈奕迅《酝酿》[WAV分轨][502M]
- 卓依婷《化蝶》2CD[WAV+CUE][1.1G]
- 群星《吉他王(黑胶CD)》[WAV+CUE]
- 齐秦《穿乐(穿越)》[WAV+CUE]
- 发烧珍品《数位CD音响测试-动向效果(九)》【WAV+CUE】
- 邝美云《邝美云精装歌集》[DSF][1.6G]
- 吕方《爱一回伤一回》[WAV+CUE][454M]