Detailed explanation of JSP xml parsing instance based on dom, jspdomxml instance

Source: Internet
Author: User

Detailed explanation of JSP xml parsing instance based on dom, jspdomxml instance

This example describes how to parse xml based on dom in JSP. We will share this with you for your reference. The details are as follows:

There are many shortcomings when I first learned how to use dom to operate xml files. I did not perform Chinese Garbled text processing or verification during the exercises! O (distinct _ distinct) 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 {// defines the Transformer f = TransformerFactory. newInstance (). newTransformer (); // sets the output encoding format f. setOutputProperty (OutputKeys. ENCODING, "UTF-8"); // build the dom source DOMSource source = new DOMSource (dom ); // specify the target PATH for storing the File. StreamResult sr = new StreamResult (new File (PATH); // execute the conversion operation f. transform (source, sr);} catch (Exception e) {e. printStackTrace () ;}// log on to the public boolean login (String name, String pwd) {boolean flag = false; try {// create Document Object Document dom = DocumentBuilderFactory based on some xml files. newInstance (). newDocumentBuilder (). parse (new File (PATH); // obtain the subnode NodeList list = dom under the user node. getElementsByTagName ("user"); // traverses the list and exits from the 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 public void insertUser (User user) {try {// create a new Document object Document dom = DocumentBuilderFactory. newInstance (). newDocumentBuilder (). newDocument (); // create the root node users Element el = dom. createElement ("users"); // Add the root node to the dom. appendChild (el); // create sub-node Element e2 = dom. createElement ("user"); // Add the subnode to the root node el. appendChild (e2); // obtain the List of existing information in the xml file <User> users = this. selectUser (); for (int I = 0; I <users. size (); I ++) {// create the node user Element el3 = dom. createElement ("user"); User us = users. get (I); // set the node attributes (name, pwd, email) el3.setAttribute ("name", us. getName (); el3.setAttribute ("pwd", us. getPwd (); el3.setAttribute ("email", us. getEmail (); // Add it 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 {// create dom Document dom = DocumentBuilderFactory based on the existing xml file. newInstance (). newDocumentBuilder (). parse (new File (PATH); // obtain the subnode NodeList list = dom under all user nodes. getElementsByTagName ("user"); for (int I = 0; I <list. getLength (); I ++) {User 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;} // modify the public void updateUser (User user) {try {// create dom Document dom = DocumentBuilderFactory according to some xml files. newInstance (). newDocumentBuilder (). parse (new File (PATH); // obtain the subnode NodeList list = dom under the user node. getElementsByTagName ("user"); // traverse list for (int I = 0; I <list. getLength (); I ++) {Element el = (Element) list. item (I); // 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 public boolean deleteUser (String name) {try {// create the domcumet object Document dom = DocumentBuilderFactory based on an xml file. newInstance (). newDocumentBuilder (). parse (new File (PATH); // obtain the subnode NodeList list = dom under the user node. getElementsByTagName ("user"); // traverse 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 ;} // search for public User findByName (String name) {User user = new User () according to the name; try {// create the document Object Document dom = DocumentBuilderFactory according to the subsequent xml file. newInstance (). newDocumentBuilder (). parse (new File (PATH); // obtain the subnode set NodeList list = dom under the user node. 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 User; public user getUser () {return User;} public void setUser (user 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 ";}/*** login * @ 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>

Four 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"> 

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

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

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

I learned the user. xml file used

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

I hope this article will help you with jsp program design.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.