JSP parsing xml example based on dom

  • 2021-08-21 21:06:19
  • OfStack

In this paper, an example is given to explain the method of JSP parsing xml based on dom. Share it for your reference, as follows:

For the first time, I learned to operate xml files with dom. There are many shortcomings. Niu Ren gives some suggestions. I didn't do garbled processing in Chinese during practice, and I didn't do verification! O (φ _ φ) O ~

Entity class: 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;
 }
}

Data access layer interface: 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);
}

Interface Implementation Class: UserDaoImpl


public class UserDaoImpl implements UserDao {
 private static final String PATH="xml File path ";
 private void build(Document dom) {
 try {
  // Define a converter 
  Transformer f = TransformerFactory.newInstance().newTransformer();
  // Set the encoding format of the output 
  f.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
  // Build dom Source 
  DOMSource source = new DOMSource(dom);
  // Specify the target strength of file storage 
  StreamResult sr = new StreamResult(new File(PATH));
  // Perform a conversion operation 
  f.transform(source, sr);
 } catch (Exception e) {
  e.printStackTrace();
 }
 }
 // Landing 
 public boolean login(String name, String pwd) {
 boolean flag = false;
 try {
  // According to some xml File creation Document Object 
  Document dom = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File(PATH));
  // Get user Child nodes under the node 
  NodeList list = dom.getElementsByTagName("user");
  // Traversal list Data matching exits 
  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;
 }
 // Add operation 
 public void insertUser(User user) {
 try {
  // Create a brand new Document Object 
  Document dom = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
  // Create a root node users
  Element el = dom.createElement("users");
  // Add the root node to the dom Medium 
  dom.appendChild(el);
  // Create child nodes 
  Element e2 = dom.createElement("user");
  // Add child nodes to the root node 
  el.appendChild(e2);
  // Acquire xml Existing information in the file 
  List<User> users = this.selectUser();
  for(int i = 0; i < users.size(); i++){
  // Create Node user
  Element el3 = dom.createElement("user");
  User us =users.get(i);
  // Set the properties of the node ( name,pwd,email ) 
  el3.setAttribute("name", us.getName());
  el3.setAttribute("pwd", us.getPwd());
  el3.setAttribute("email", us.getEmail());
  // Add to the root node 
  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();
 }
 }
 // Query operation 
 public List<User> selectUser() {
 List<User> userList = new ArrayList<User>();
 try {
  // According to the existing xml File creation dom
  Document dom = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File(PATH));
  // Get all user Child nodes under the node 
  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;
 }
 // Modification operation 
 public void updateUser(User user) {
 try {
  // According to some xml File creation dom
  Document dom = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File(PATH));
  // Get user Child nodes under the node 
  NodeList list = dom.getElementsByTagName("user");
  // Traversal list
  for(int i = 0;i < list.getLength();i++) {
  Element el = (Element)list.item(i);
  // According to name Property to modify 
  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();
 }
 }
 // Delete operation 
 public boolean deleteUser(String name) {
 try {
  // According to the following xml File creation domcumet Object 
  Document dom = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File(PATH));
  // Get user Child nodes under the node 
  NodeList list = dom.getElementsByTagName("user");
  // Traversal 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;
 }
 // According to name Find 
 public User findByName(String name) {
 User user = new User();
 try {
  // According to later xml File creation document Object 
  Document dom = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File(PATH));
  // Get user Child node collection under node 
  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;
 }
}

Business logic layer interface: 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);

Interface Implementation Class: 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);
 }
}

Control layer: 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";
 }
 /**
 *  Landing 
 * @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;
 }
 /**
 *  Modify 
 * @return
 */
 public String update(){
 userService.updateUser(user);
 return "update";
 }
 /**
 *  Edit 
 * @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";
 }
 /**
 *  Delete 
 * @return
 */
 public String delete(){
 HttpServletRequest request = ServletActionContext.getRequest();
 String name = request.getParameter("uName");
 boolean flag = userService.deleteUser(name);
 System.out.println(flag);
 return SUCCESS;
 }
  /**
   *  Add 
   * @return
   */
 public String insert(){
 userService.insertUser(user);
 return "insert";
 }
}

struts. xml configuration (my 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 configuration


<?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>

4 pages: 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"> Home page </a>|<a href="insert.jsp"> Registration </a>
  <form action="login.action" method="post">
  <table>
  <tr>
    <td>  User name: </td><td><input name="user.name" type="text"></td>
  </tr>
  <tr>
    <td>  Password: </td><td><input type="password" name="user.pwd"></td>
  </tr>
  <tr>
    <td colspan="2" align="center"><input type="submit" value=" Login "></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"> Registration </a>
  <table border="1">
  <tr>
   <td align="center" colspan="6"><font size="+3"> User list </font></td>
  </tr>
   <tr>
    <td> Serial number </td><td> User name </td><td> Password </td><td> Mailbox </td><td> Delete </td><td> Edit </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}"> Delete </a></td><td><a href="edit.action?uName=${u.name }"> Edit </a></td>
    </tr>
  </c:forEach>
  </table>
 </body>
</html>

insert.jsp


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);
}

0

update.jsp


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);
}

1

The user. xml file I used for my study


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);
}

2

I hope this article is helpful to everyone's jsp programming.


Related articles: