XML by Example- P10

Chia sẻ: Thanh Cong | Ngày: | Loại File: PDF | Số trang:50

0
43
lượt xem
9
download

XML by Example- P10

Mô tả tài liệu
  Download Vui lòng tải xuống để xem tài liệu đầy đủ

Tham khảo tài liệu 'xml by example- p10', công nghệ thông tin, kỹ thuật lập trình phục vụ nhu cầu học tập, nghiên cứu và làm việc hiệu quả

Chủ đề:
Lưu

Nội dung Text: XML by Example- P10

  1. The Data Tier 435 Listing 12.17: XMLServerConsole.java package com.psol.xcommerce; import java.io.*; import java.sql.*; import javax.servlet.*; import javax.servlet.http.*; /** * Simple console to create database and enter data in * the SQL database. * * @version Dec 23, 1999 * @author Benoît Marchal */ public class XMLServerConsole extends HttpServlet { /** * handles GET request * @param request HTTP request * @param response hold the response * @exception SerlvetException error handling the request * @exception IOException error writing the reply */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doProcess(request,response); } /** * handles GET request * @param request HTTP request * @param response hold the response * @exception SerlvetException error handling the request continues
  2. 436 Chapter 12: Putting It All Together: An e-Commerce Example Listing 12.17: continued * @exception IOException error writing the reply */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doProcess(request,response); } /** * GET and POST requests are forwarded here * @param request HTTP request * @param response hold the response * @exception SerlvetException error handling the request * @exception IOException error writing the reply */ protected void doProcess(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String sqlDriver = getInitParameter(“sql.driver”), sqlURL = getInitParameter(“sql.url”), sqlUser = getInitParameter(“sql.user”), sqlPassword = getInitParameter(“sql.password”); try { Class.forName(sqlDriver); Connection connection = DriverManager.getConnection(sqlURL, sqlUser, sqlPassword); try { String action = request.getParameter(“action”); if(null != action) { if(action.equalsIgnoreCase(“create”)) doUpdates(request,connection,createStatements);
  3. The Data Tier 437 else if(action.equalsIgnoreCase(“drop”)) doUpdates(request,connection,dropStatements); else if(action.equalsIgnoreCase(“delete”)) doDelete(request,connection); else if(action.equalsIgnoreCase(“insert”)) doInsert(request,connection); } doPage(request,response,connection); } finally { connection.close(); } } catch(Exception e) { throw new ServletException(e); } } /** * drop and create statements to delete/create the database */ private static final String[] dropStatements = { “drop table products”, “drop table orders”, }; private static final String[] createStatements = { “create table products (id integer not null constraint idconstraint pri- mary key,” + “name varchar(50),manufacturer varchar(50),” + “img varchar(30),warranty varchar(20),” + “description varchar(150),price real)”, “create table orders (name varchar(50),” + “street varchar(100),region varchar(50),” + “postal_code varchar(15),locality varchar(50),” + continues
  4. 438 Chapter 12: Putting It All Together: An e-Commerce Example Listing 12.17: continued “country varchar(25),email varchar(50),” + “productid integer,productname varchar(50),” + “productprice real,productquantity integer)” }; /** * execute a number of updates on the database * (typically to create schema) * @param request HTTP request * @param connection database connection * @param statements statements to execute * @throw SQLException one statement throw an exception */ protected void doUpdates(HttpServletRequest request, Connection connection, String[] statements) throws SQLException { Statement stmt = connection.createStatement(); SQLException e = null; try { for(int i = 0;i < statements.length;i++) try { stmt.executeUpdate(statements[i]); } catch(SQLException x) { e = e != null ? e : x; } if(null != e) { throw e; } } finally { stmt.close(); } }
  5. The Data Tier 439 /** * delete one product from the database * @param request HTTP request * @param connection database connection * @return the form to display (the result screen if you like) */ protected void doDelete(HttpServletRequest request, Connection connection) throws SQLException { PreparedStatement stmt = connection.prepareStatement( “delete from products where id = ?”); try { String id = request.getParameter(“id”); stmt.setInt(1,Integer.parseInt(id)); stmt.executeUpdate(); } finally { stmt.close(); } } /** * create a new product in the database * @param request HTTP request * @param connection database connection * @return the form to display (the result screen if you like) */ protected void doInsert(HttpServletRequest request, Connection connection) throws SQLException, Exception { String id = request.getParameter(“id”), name = request.getParameter(“name”), continues
  6. 440 Chapter 12: Putting It All Together: An e-Commerce Example Listing 12.17: continued manufacturer = request.getParameter(“manufacturer”), image = request.getParameter(“image”), warranty = request.getParameter(“warranty”), description = request.getParameter(“description”), price = request.getParameter(“price”); PreparedStatement stmt = connection.prepareStatement( “insert into products (id,name,manufacturer,img,” + “warranty,description,price) values(?,?,?,?,?,?,?)”); try { stmt.setString(1,id); stmt.setString(2,name); stmt.setString(3,manufacturer); stmt.setString(4,image); stmt.setString(5,warranty); stmt.setString(6,description); stmt.setString(7,price); stmt.executeUpdate(); } finally { stmt.close(); } } /** * check whether the schema has been created * @return true if the schema is complete, false otherwise */ protected boolean isSchemaCreated(Connection connection) throws SQLException { // ask the name of all the tables in the database // check if one of them is “products” DatabaseMetaData meta = connection.getMetaData(); ResultSet rs = meta.getTables(null,null,null,new String[] { “TABLE” });
  7. The Data Tier 441 int found = 0; while(rs.next()) { String tableName = rs.getString(“TABLE_NAME”); if(tableName.equalsIgnoreCase(“products”) || tableName.equalsIgnoreCase(“orders”)) found++; } rs.close(); return 2 == found; } /** * display the page, etc. * @param request HTTP request * @param connection database connection */ protected void doPage(HttpServletRequest request, HttpServletResponse response, Connection connection) throws SQLException, IOException { Writer writer = response.getWriter(); writer.write(“XML Server Console” + “”); Statement stmt = connection.createStatement(); try { if(isSchemaCreated(connection)) { writer.write(“”); writer.write(“Identifier:”); writer.write(“”); continues
  8. 442 Chapter 12: Putting It All Together: An e-Commerce Example Listing 12.17: continued writer.write(“Name:”); writer.write(“”); writer.write(“Manufacturer:”); writer.write(“”); writer.write(“Image:”); writer.write(“”); writer.write(“Warranty:”); writer.write(“”); writer.write(“Description:”); writer.write(“”); writer.write(“Price:”); writer.write(“”); writer.write(“”); writer.write(“”); writer.write(“”); ResultSet rs = stmt.executeQuery(“select id, name from products”); writer.write(“”); while(rs.next()) { writer.write(“”); writer.write(rs.getString(2)); writer.write(“”); writer.write(“ ”); writer.write(“”);
  9. The Data Tier 443 writer.write(“”); writer.write(“”); } writer.write(“”); rs = stmt.executeQuery(“select name, “ + “productname from orders”); writer.write(“”); while(rs.next()) { writer.write(“”); writer.write(rs.getString(1)); writer.write(“”); writer.write(rs.getString(2)); writer.write(“”); } writer.write(“”); } writer.write(“”); writer.write(“”); writer.write(“”); writer.write(“”); writer.write(“”); writer.write(“”); writer.write(“”); writer.write(“”); } finally continues
  10. 444 Chapter 12: Putting It All Together: An e-Commerce Example Listing 12.17: continued { stmt.close(); } writer.write(“”); writer.flush(); } } Viewer and Editor XMLi is a smaller merchant. It doesn’t have a Web site or a database. XMLi creates its list of products manually with the editor shown in Listings 12.18, 12.19, and 12.20. Listing 12.18 is the Java servlet, Listing EXAMPLE 12.19 is the JavaScript file, and Listing 12.20 is the XSL style sheet. You edit a list of products through a URL like http://localhost /editor?merchant=xmli. Listing 12.18: Editor.java package com.psol.xcommerce; import java.io.*; import org.w3c.dom.*; import javax.servlet.*; import javax.servlet.http.*; /** * Editor is a web-tool to create product lists * for smaller merchants. * * @version Sep 10, 1999 * @author Benoît Marchal */ public class Editor extends HttpServlet { /** * the editor’s style sheet */ protected Document styleSheet;
  11. Viewer and Editor 445 /** * initializes the servlet, read the style sheet * @exception could not read the style sheet */ public void init() throws ServletException { String fname = getInitParameter(“editor.xsl”); styleSheet = XMLUtil.parse(fname); } /** * process GET requests * @param request request received from the client * @param response response to the client */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String merchant = request.getParameter(“merchant”), fname = getInitParameter(merchant + “.xml”); if(null == merchant || null == fname) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } Document document = XMLUtil.parse(fname); XMLUtil.transform(document, styleSheet, response.getWriter(), response.getCharacterEncoding()); } /** * handle POST method, HttpServlet forward POST request from service() continues
  12. 446 Chapter 12: Putting It All Together: An e-Commerce Example Listing 12.18: continued * to this method * @param request the request received from the client * @param response interface to the client */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String merchant = request.getParameter(“merchant”), fname = getInitParameter(merchant + “.xml”); if(null == merchant || null == fname) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } String pwdRequest = request.getParameter(“pwd”), pwdCheck = getInitParameter(merchant + “.pwd”), xml = request.getParameter(“xmldata”); if(null != pwdCheck && !pwdCheck.equals(pwdRequest)) { response.sendError(HttpServletResponse.SC_FORBIDDEN); return; } Writer writer = new FileWriter(fname); writer.write(xml); writer.close(); writer = response.getWriter(); writer.write(“Confirmation”); writer.write(“”); writer.write(“Your changes were saved as follow:”); XMLUtil.writeInXML(writer,xml); writer.write(“”); writer.flush(); } }
  13. Viewer and Editor 447 Listing 12.19: Editor.js // editor.js, common code for Editor var products = new Array(); function addProduct(form) { // collects data from the form var id = form.id.value, name = form.name.value, price = form.price.value, description = form.description.value; doAddProduct(form,id,name,price,description); } function doAddProduct(form,id,name,price,description) { var productList = form.productlist, product = new Product(id,name,price,description); // arrays are zero-based so products.length points // to one past the latest product // JavaScript automatically allocates memory var pos = products.length; products[pos] = product; var option = new Option(name + “ (“ + price + “)”,pos); productList.options[productList.length] = option; } function deleteProduct(form) { var productList = form.productlist, pos = productList.selectedIndex; if(pos != -1) continues
  14. 448 Chapter 12: Putting It All Together: An e-Commerce Example Listing 12.19: continued { var product = productList.options[pos].value; productList.options[pos] = null; products[product] = null; } } function exportProduct(form) { var xmlCode = “”, merchant = form.merchant.value, attribute = “merchant=’” + merchant + “‘“; var i; for(i = 0;i < products.length;i++) if(products[i] != null) xmlCode += products[i].toXML(); xmlCode = element(“products”,attribute,xmlCode); form.xmldata.value = “” + xmlCode; } function resetAll(form,document) { priceList = null; form.output.value = “”; } function element(name,attributes,content) { var result = “”; result += content; result += “\r”;
  15. Viewer and Editor 449 return result; } function escapeXML(string) { var result = “”, i, c; for(i = 0;i < string.length;i++) { c = string.charAt(i); if(c == ‘
  16. 450 Chapter 12: Putting It All Together: An e-Commerce Example Listing 12.19: continued result += element(“description”,””, escapeXML(this.description)); return element(“product”,attrs,result); } Listing 12.20: editor.xsl Product List Editor function load(form) { doAddProduct(form, “”, “”, “”, “”); } // ID: Name: Price:
  17. Viewer and Editor 451 Description: Password: Note that this editor cannot start from an empty file because it needs the merchant name in the style sheet. When creating a new merchant, you must also create the following file (an empty list of products): Listing 12.21 and the accompanying style sheet in Listing 12.22 display the orders for XMLi. Listing 12.21: Viewer.java package com.psol.xcommerce; import java.io.*; import org.w3c.dom.*; continues
  18. 452 Chapter 12: Putting It All Together: An e-Commerce Example Listing 12.21: continued import javax.servlet.*; import javax.servlet.http.*; /** * Viewer is a web-tool to view orders * for smaller merchants. * * @version Sep 10, 19999 * @author Benoît Marchal */ public class Viewer extends HttpServlet { /** * the viewer’s style sheet */ protected Document styleSheet; /** * initializes the servlet, read the style sheet * @exception could not read the style sheet */ public void init() throws ServletException { String fname = getInitParameter(“viewer.xsl”); styleSheet = XMLUtil.parse(fname); } /** * process GET requests * @param request request received from the client * @param response response to the client */ protected void doGet(HttpServletRequest request, HttpServletResponse response)
  19. Viewer and Editor 453 throws IOException, ServletException { String merchant = request.getParameter(“merchant”), path = getInitParameter(merchant + “.orders”), fname = request.getParameter(“fname”); if(null == merchant || null == path) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } if(null == fname) { File file = new File(path); String[] files = file.list(); Writer writer = response.getWriter(); writer.write(“Order list”); writer.write(“”); for(int i = 0;i < files.length;i++) { writer.write(“”); writer.write(files[i]); writer.write(“”); } writer.write(“”); writer.flush(); } else { File file = new File(path,fname); Document document = XMLUtil.parse(file.getPath()); XMLUtil.transform(document, continues
  20. 454 Chapter 12: Putting It All Together: An e-Commerce Example Listing 12.21: continued styleSheet, response.getWriter(), response.getCharacterEncoding()); } } } Listing 12.22: viewing.xsl Order You have received the following order from: Name: Street: Region: ZIP or postal code: Locality: Country:
Đồng bộ tài khoản