1. Trang chủ
  2. » Công Nghệ Thông Tin

programming XML by Example phần 8 pptx

53 156 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 53
Dung lượng 369,4 KB

Nội dung

How XML Helps As soon as there are two or more parties, they need to communicate. Currently, two approaches are particularly popular for client/server applica- tions: • middleware such as CORBA (Common Object Request Broker Architecture), DCOM (Distributed Component Object Model), or RPC (Remote Procedure Call) • exchange formats such as HTML or XML Middleware I won’t cover middleware in great detail (this is an XML book, not a middle- ware book), but I want to provide you with enough information for a com- parison. The basic idea behind middleware is to reduce the effort required to write distributed applications. Networks are not always safe, reliable, and dependable. In fact, one could argue that they are exactly the opposite. To work around these limitations, programmers have to implement specific protocols. It is not uncommon for network-specific code to amount to more than 10 times the business code. This process takes time and is not very productive. Indeed, the time spent wrestling with the network and its security is not spent solving actual business problems. Middleware includes tools that deal with the network. For example, a net- work might fail but middleware has logic to gracefully recover from these failures. Also, on a network several computers need to collaborate. Middleware offers tools to manage the interaction between these com- puters. Middleware is based on specific protocols but, instead of overwhelming pro- grammers with details, it hides them. Programmers are free to concentrate on business issues and, therefore, be more productive. Listing 11.1 illustrates this. This is a simple CORBA client that appends one line to an order and confirms it. A server maintains the order. Listing 11.1: Small CORBA Example import org.omg.CORBA.*; public class StockExchangeClient { static public void main(String[] args) 356 Chapter 11: N-Tiered Architecture and XML EXAMPLE 13 2429 CH11 2.29.2000 2:24 PM Page 356 { String order = args[0], product = args[1]; int quantity = Integer.parseInt(args[2]); ORB orb = ORB.init(args,null); Order remoteOrder = OrderHelper.bind(orb,order); remoteOrder.appendLine(product,quantity); remoteOrder.confirm(); } } Listing 11.1 is interesting because you can hardly tell it is a distributed application. The only lines that explicitly deal with networks are these two: ORB orb = ORB.init(args,null); Order remoteOrder = OrderHelper.bind(orb,order); and they are not very difficult. Without going into any details, they connect to an order on the server. More interestingly, the application can manipu- late the order, which is a server object, just as if it were a client object: remoteOrder.appendLine(product,quantity); remoteOrder.confirm(); That’s the power of middleware; it completely hides the distributed aspect. Experience shows that middleware works better on LANs or intranets than on cross-enterprise applications. This is because, with middleware, the client directly manipulates objects on the server. This leads to a very tight coupling between the client and the server. It is therefore simpler if both parties are controlled by the same organization. NOTE Middleware gurus are quick to point out that it doesn’t have to be that way. Indeed there are several mechanisms, including dynamic invocation, that support very flexible coupling with middleware. While it is correct technically, in practice, experience shows that most solutions based on middleware are relatively inflexible and are therefore best suited for internal use. Common Format For applications that work across several organizations, it is easier to exchange documents in a common format. This is how the Web works: A Web server requests HMTL documents from a Web browser. This process has proved to scale well to millions of users. 357 How XML Helps 13 2429 CH11 2.29.2000 2:24 PM Page 357 HTML is a good format but it is intended for human consumption only. XML, as you have seen, is similar but can be manipulated by applications. XCommerce illustrates how it works (see Figure 11.5). 358 Chapter 11: N-Tiered Architecture and XML EXAMPLE Figure 11.5: The Web mall, XCommerce As you can see, this is an n-tiered application: The client converses with the mall server. The mall server converses with the XML data server. The data server itself may be connected to a database server. XML has many strong points for this setup: • XML is extensible, which allows the different partners to build on commonalities while retaining the option to extend the basic services where appropriate. • XML is structure-rich, which allows the middle server to process prod- uct information (such as extracting prices). • XML is versatile, therefore most data in the application are stored in XML. In particular, XML is used for configuration information (the list of merchants), for product information, and to store the orders them- selves. • XML scales well. Small merchants can prepare product lists manually with an editor while larger merchants can generate the list from a database. • As a secondary benefit of scalability, XML gives the merchants lots of flexibility in deploying their solutions. A merchant can start with a simple solution and upgrade as the business expands. • XML is based on the Web; therefore, it is often possible to reuse HTML investments. 13 2429 CH11 2.29.2000 2:24 PM Page 358 • XML is textual, which simplifies testing and debugging (this should not be neglected because very few applications work flawlessly the first time). • XML is cost effective to deploy because many vendors support it; com- panion standards are also available. XML for the Data Tiers XML brings its emphasis on structure, its extensibility, its scalability, and its versatility to the data tiers. This chapter has discussed the structure aspect at length already, so let’s review the other features. Extensibility Figure 11.6 is the structure for the list of products. Listing 11.2 is an example of a list of products. 359 XML for the Data Tiers Figure 11.6: Structure for the list of products Listing 11.2: Product List in XML <?xml version=”1.0”?> <products merchant=”emailaholic”> <product id=”0”> <name>Ultra Word Processor</name> <description>More words per minute than the competition.</description> <price>$799.99</price> </product> <product id=”1”> <name>Super Calculator</name> <description>Cheap and reliable with power saving.</description> <price>$5.99</price> </product> continues 13 2429 CH11 2.29.2000 2:24 PM Page 359 <product id=”2”> <name>Safest Safe</name> <description>Choose the authentic Safest Safe.</description> <price>$1,999.00</price> </product> </products> ✔ Obviously, some merchants will want to provide more information than is supported in the list of products. For example, they will want to add images, manufacturer information, and more. This is possible using the technique introduced in the section “Building on XML Extensibility” in Chapter 10 (page 312). Listing 11.3 illustrates how one merchant can publish additional product information. The merchant has to provide a style sheet to display the extra information to the buyer. Listing 11.3: Extending the Core Format <?xml version=”1.0”?> <products merchant=”emailaholic” xmlns:em=”http://www.emailaholic.com/xt/1.0”> <product id=”0”> <name>Ultra Word Processor</name> <em:manufacturer>Ultra Word Inc.</em:manufacturer> <em:image>wordprocessor.jpg</em:image> <em:warranty>1 month</em:warranty> <description>More words per minute than the competition.</description> <price>$799.99</price> </product> <product id=”1”> <name>Super Calculator</name> <em:manufacturer>United Calculators Corp.</em:manufacturer> <em:image>calculator.jpg</em:image> <em:warranty>6 months</em:warranty> <description>Cheap and reliable with power saving.</description> <price>$5.99</price> </product> <product id=”2”> <name>Safest Safe</name> 360 Chapter 11: N-Tiered Architecture and XML Listing 11.2: continued 13 2429 CH11 2.29.2000 2:24 PM Page 360 <em:manufacturer>Safe Safe Inc.</em:manufacturer> <em:image>safe.jpg</em:image> <em:warranty>lifetime</em:warranty> <description>Choose the authentic Safest Safe.</description> <price>$1,999.00</price> </product> </products> Scalability 1. Currently, XCommerce has two merchants. Emailaholic, the first mer- chant, is a large company. It has a Web site with a database of prod- ucts available online. It dynamically generates XML documents from its database. Listing 11.4 is an extract from a servlet that generates the XML document for Emailaholic. The complete listing is in Chapter 12, “Putting It All Together: An e-Commerce Example.” Listing 11.5 is a server that Emailaholic uses to manage its database; again, the complete listing is in Chapter 12. Listing 11.4 generates XML; Listing 11.5 generates HTML for a similar document. Compare both listings and see how similar they are. Both are based on the same Web technology and both are based on very similar markup lan- guages. For Emailaholic, it is not much more difficult to write Listing 11.4, which uses the newer XML, than to write Listing 11.5, which uses the well- known HTML technology. In practice, it means that Emailaholic can reuse its HTML experience with XML. What does it all mean? It means that adding XML in a Web project is easy. XML is popular because it is that simple. It is also popular because it is based on many techniques that are already well known through HTML; therefore, people are rapidly productive with HTML. I have seen projects where people would take their HTML-based application and turn it into an XML application in a matter of days, not weeks. Listing 11.4: Writing an XML Document protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType(“application/xml”); 361 XML for the Data Tiers EXAMPLE continues 13 2429 CH11 2.29.2000 2:24 PM Page 361 Writer writer = response.getWriter(); String sqlDriver = getInitParameter(“sql.driver”), sqlURL = getInitParameter(“sql.url”), sqlUser = getInitParameter(“sql.user”), sqlPassword = getInitParameter(“sql.password”), merchant = getInitParameter(“merchant”); writer.write(“<?xml version=\”1.0\”?>”); writer.write(“<products merchant=\””); writer.write(merchant); writer.write(“\” xmlns:em=\”http://www.emailaholic”); writer.write(“.com/xt/1.0\”>”); try { Class.forName(sqlDriver); Connection connection = DriverManager.getConnection(sqlURL, sqlUser, sqlPassword); try { Statement stmt = connection.createStatement(); try { ResultSet rs = stmt.executeQuery(“select id, name, “ + “manufacturer, image, warranty, “ + “description, price from products”); while(rs.next()) { writer.write(“<product id=\””); writer.write(String.valueOf(rs.getInt(1))); writer.write(“\”><name>”); writer.write(rs.getString(2)); writer.write(“</name><em:manufacturer>”); writer.write(rs.getString(3)); writer.write(“</em:manufacturer><em:image>”); writer.write(rs.getString(4)); 362 Chapter 11: N-Tiered Architecture and XML Listing 11.4: continued 13 2429 CH11 2.29.2000 2:24 PM Page 362 writer.write(“</em:image><em:warranty>”); writer.write(rs.getString(5)); writer.write(“</em:warranty><description>”); writer.write(rs.getString(6)); writer.write(“</description><price>”); writer.write(formatter.format(rs.getDouble(7))); writer.write(“</price></product>”); } } finally { stmt.close(); } } finally { connection.close(); } } catch(ClassNotFoundException e) { throw new ServletException; } catch(SQLException e) { throw new ServletException(e); } writer.write(“</products>”); writer.flush(); } Listing 11.5: Writing an HTML Document protected void doPage(HttpServletRequest request, HttpServletResponse response, Connection connection) throws SQLException, IOException { Writer writer = response.getWriter(); 363 XML for the Data Tiers continues 13 2429 CH11 2.29.2000 2:24 PM Page 363 writer.write(“<HTML><HEAD><TITLE>XML Server Console” + “</TITLE></HEAD><BODY>”); Statement stmt = connection.createStatement(); try { // deleted, see chapter 12 for complete listing ResultSet rs = stmt.executeQuery(“select id, name from products”); writer.write(“<TABLE>”); while(rs.next()) { writer.write(“<TR><TD>”); writer.write(rs.getString(2)); writer.write(“</TD><TD><FORM ACTION=\””); writer.write(request.getServletPath()); writer.write(“\” METHOD=\”POST\”>”); writer.write(“ <INPUT TYPE=\”SUBMIT\””); writer.write(“ VALUE=\”Delete\”>”); writer.write(“<INPUT TYPE=\”HIDDEN\””); writer.write(“ NAME=\”action\” VALUE=\”delete\”>”); writer.write(“</FORM></TD></TR>”); } writer.write(“</TABLE>”); // deleted, see chapter 12 for complete listing } finally { stmt.close(); } writer.write(“</BODY></HTML>”); writer.flush(); } 2. XMLi is the second merchant. XMLi is a smaller company and it doesn’t have a Web site. Fortunately, there is more than one way to generate XML documents. A small merchant, like XMLi, can prepare its list of products (in XML) manually and upload the list to the mall site. Figure 11.7 shows the editor XMLi uses. 364 Chapter 11: N-Tiered Architecture and XML Listing 11.4: continued 13 2429 CH11 2.29.2000 2:24 PM Page 364 ✔ This editor is nothing more than a style sheet and JavaScript so it is very simple to deploy. The source code is in the section “Viewer and Editor” in Chapter 12 (page 444). 365 XML for the Data Tiers Figure 11.7: Editing the list of products Versatility The Web mall needs to forward the orders to the merchants. When a visitor buys from the Web site, the order is also represented as an XML document. So, XML serves all of the data exchange needs. Listing 11.6 shows a sample order. Listing 11.6: An Order in XML <?xml version=”1.0”?> <order> <buyer name=”John Doe” street=”34 Fountain Square Plaza” region=”OH” postal-code=”45202” locality=”Cincinnati” country=”US” email=”jdoe@emailaholic.com”/> <product quantity=”1” id=”xmli” name=”XML Book” price=”$19.99”/> </order> EXAMPLE 13 2429 CH11 2.29.2000 2:24 PM Page 365 [...]... emailaholic./.Servlet. /xml : xml= com.psol.xcommerce.XMLServer? ➥./properties/xmlserver.prp emailaholic./.Servlet./console : console=com.psol.xcommerce ➥XMLServerConsole?./properties/xmlserver.prp 14 2429 CH12 2.29.2000 2:25 PM Page 383 Building XCommerce 383 Listing 12.2: shop.prp merchants .xml= ./data/merchants .xml merchants.xsl=./xsl/merchants.xsl xmli.orders=./xmli Listing 12.3: xmlserver.prp merchant=emailaholic... sql.password=masterkey Listing 12.4: viewedit.prp editor.xsl=./xsl/editor.xsl viewer.xsl=./xsl/viewer.xsl # XMLi products xmli .xml= ./data/xmli .xml xmli.pwd=xmli xmli.orders=./xmli Directories The configuration files require that the files be organized in the following directories: • data contains the list of merchants and an XMLi product list • xsl contains the style sheet for the shop, with the exception of Emailaholic-specific... add tags to the product description and provide a style sheet that takes advantage of the new tags Listing 11 .8: The Emailaholic Style Sheet < ?xml version=”1.0” encoding=”ISO -88 59-1”?> ... Listing 11.10: Emailaholic Style Sheet for Product < ?xml version=”1.0” encoding=”ISO -88 59-1”?> 13 2429 CH11 2.29.2000 2:24 PM Page 371 XML on the Middle Tier 371 ... images • xmli is an empty directory where XMLi orders are stored Compiling and Running Before running this application, you must compile all the Java files Use the Java compiler such as: javac -classpath c:\jetty\lib\javax.servlet.jar; ➥c:\lotusxsl\lotusxsl.jar;c: \xml4 j \xml4 j.jar; -sourcepath ➥ Shop.java 14 2429 CH12 384 2.29.2000 2:25 PM Page 384 Chapter 12: Putting It All Together: An e-Commerce Example. .. present more or less detailed information to the user 13 2429 CH11 370 2.29.2000 2:24 PM Page 370 Chapter 11: N-Tiered Architecture and XML Listing 11.9: Product.xsl < ?xml version=”1.0” encoding=”ISO -88 59-1”?> Online Shop... Architecture and XML Figure 11.10: Product information in a browser Client The last tier is the client Ultimately, it will be possible to send XML to the client and apply style sheets on the client Currently, I would advise against sending any XML to the client It makes more sense to convert to HTML on the server There are several problems with XML on the client: • Currently, XML is supported only by the latest... realistic example 13 2429 CH11 2.29.2000 2:24 PM Page 373 XML on the Middle Tier EXAMPLE 373 If you need special processing on the client, you can always resort to JavaScript It is even possible to combine XSL and JavaScript Listing 11.11 demonstrates how to generate client-side JavaScript from a serverside XSL style sheet Listing 11.11: Generating JavaScript from XSL < ?xml version=”1.0” encoding=”ISO -88 59-1”?>... Chapter 11: N-Tiered Architecture and XML The order benefits from all the other qualities of XML In particular, the middle tier posts the order to the Emailaholic site, where it is automatically parsed and loaded into a database Orders for XMLi are not posted to a Web site because XMLi has no Web site Instead, the orders are saved in files To review its order, XMLi applies a style sheet to them Again,... Page 376 Chapter 11: N-Tiered Architecture and XML Therefore, XSL is not enough A medium-sized XML application needs code to compare documents, compile new documents, handle user authentication, and more All these features are not being covered, or not properly covered, by XSL The main options for server-side programming languages that work well with XML are Perl, JavaScript, Python, Omnimark, and . new tags. Listing 11 .8: The Emailaholic Style Sheet < ?xml version=”1.0” encoding=”ISO -88 59-1”?> <xsl:stylesheet xmlns:xsl=”http://www.w3.org/1999/XSL/Transform/” xmlns:em=”http://www.emailaholic.com/xt/1.0” xmlns=”http://www.w3.org/TR/REC-html40”> <xsl:output. for Product < ?xml version=”1.0” encoding=”ISO -88 59-1”?> <xsl:stylesheet xmlns:xsl=”http://www.w3.org/1999/XSL/Transform/” xmlns:em=”http://www.emailaholic.com/xt/1.0” xmlns=”http://www.w3.org/TR/REC-html40”> 370 Chapter. information to the user. EXAMPLE 13 2429 CH11 2.29.2000 2:24 PM Page 369 Listing 11.9: Product.xsl < ?xml version=”1.0” encoding=”ISO -88 59-1”?> <xsl:stylesheet xmlns:xsl=”http://www.w3.org/1999/XSL/Transform/” xmlns=”http://www.w3.org/TR/REC-html40”> <xsl:output

Ngày đăng: 13/08/2014, 21:21