Xml programming bible phần 7 ppt

99 249 0
Xml programming bible phần 7 ppt

Đ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

555 Chapter 21 ✦ Building XML-Based Web Applications with JDBC position = stringtofix.indexOf (textstring,position+xmlstring.length()); } return stringtofix; } Listing 21-11 shows what the Element XML output looks like for a quote in the application: Listing 21-11: Custom XML Output Generated by the GetSingleQuoteElement Class <?xml version=”1.0” encoding=”UTF-8”?> <resultset> <sql>SELECT dbo.Quotations.Quotation, dbo.Authors.AuthorName, dbo.Sources.[Source Name] FROM dbo.Quotations INNER JOIN dbo.Authors ON dbo.Quotations.AuthorID = dbo.Authors.AuthorID INNER JOIN dbo.Sources ON dbo.Quotations.SourceID = dbo.Sources.SourceID WHERE (dbo.Quotations.Quotation = ‘When the hurlyburlys done, When the battles lost and won.’) </sql> <metadata> <field name=”Quotation” datatype=”char”/> <field name=”AuthorName” datatype=”char”/> <field name=”Source Name” datatype=”char”/> </metadata> <records> <record rownumber=”1”> <Quotation>When the hurlyburlys done, When the battles lost and won.</Quotation> <AuthorName>Shakespeare, William</AuthorName> <SourceName>Macbeth</SourceName> </record> </records> </resultset> Listing 21-12 is called when a user clicks on a quote and the Attribute XML (Table=Element, Field Name=Attribute) option is chosen from the output format combo box. The Quote text is passed to the GetSingleQuoteAttribute class. This class generates another JDBC query to the SQL Server instance. The query returns a result set containing all of the columns in the quotations Table related to the selected quote. i538292 ch21.qxd 8/18/03 8:44 AM Page 555 556 Part IV ✦ Relational Data and XML Next, the result set and the SQL query string are passed to the buildAttribute XML class, which is used to build an XML document. The buildAttributeXML class is shown in Listing 21-13. Listing 21-12: The GetSingleQuoteAttribute Class public String GetSingleQuoteAttribute(String PassedQuote) { String XMLDoc=null; String sql = “SELECT dbo.Quotations.Quotation, dbo.Authors.AuthorName, dbo.Sources.[Source Name] FROM dbo.Quotations INNER JOIN dbo.Authors ON dbo.Quotations.AuthorID = dbo.Authors.AuthorID INNER JOIN dbo.Sources ON dbo.Quotations.SourceID = dbo.Sources.SourceID WHERE (dbo.Quotations.Quotation = ‘“+PassedQuote.trim()+”’)”; try { Class.forName(“com.microsoft.jdbc.sqlserver.SQLServerDriver”); Connection conn = DriverManager.getConnection (“jdbc:microsoft:sqlserver://127.0.0.1:1433; User=jdbcUser;Password=jdbcUser; DatabaseName=XMLProgrammingBible”); Statement s = conn.createStatement(); ResultSet rs = s.executeQuery(sql); XMLDoc = buildAttributeXML(rs, sql); rs.close(); conn.close(); } catch(Exception e) { e.printStackTrace(); } return XMLDoc ; } } Listing 21-13 shows the buildAttributeXML class that is used to create a custom element-based XML document for the SQL Server output. It’s very similar to the buildElementXML class, but this time the code produces row data as attributes of a single element, instead of nested elements under a records element. i538292 ch21.qxd 8/18/03 8:44 AM Page 556 557 Chapter 21 ✦ Building XML-Based Web Applications with JDBC The first thing the buildAttributeXML class does is create a new StringBuffer in which to store the XML document. An XML document declaration is sent to the StringBuffer, along with a root element, called resultset. Next, an element called sql is created, which contains the SQL Server query that was used to gener- ate the result set. We also retrieve the metadata into the XML document, which can be used by applications that work with the XML document to parse the XML values by data type and column name. We also use the metadata column name to name the elements that represent columns in the XML document. Row data is returned in a single records element. Because this example returns a single row, a single element contains all of the column values as attributes. Column values are stored in text data, and column names are represented as element names. The entityRefs class converts any illegal XML characters in the text data (&, ‘, >, <, and “) into legal entity references for those values. The buildAttributeXML class retrieves the XML document from the String Buffer and returns the XML document to the calling object as a string. Listing 21-13: The buildAttributeXML Class String buildAttributeXML(ResultSet rs, String sql) { StringBuffer strResults = new StringBuffer(“<?xml version=\”1.0\” encoding=\”UTF-8\”?>\r\n<resultset>\r\n”); try { strResults.append(“<sql>” + sql +” </sql>\r\n”); ResultSetMetaData rsMetadata = rs.getMetaData(); int intFields = rsMetadata.getColumnCount(); strResults.append(“<metadata>\r\n”); for(int h =1; h <= intFields; h++) { strResults.append(“<field name=\”” + rsMetadata.getColumnName(h) + “\” datatype=\”” + rsMetadata.getColumnTypeName(h) + “\”/>\r\n”); } strResults.append(“</metadata>\r\n<records>\r\n”); int rownumber= 0; while(rs.next()) { rownumber++; strResults.append(“<record rownumber=\””+rownumber+”\””); for(int i =1; i <= intFields; i++) { strResults.append(“ “+rsMetadata.getColumnName(i) + “ = \”” + entityRefs(rs.getString(i).trim()) + “\””); } Continued i538292 ch21.qxd 8/18/03 8:44 AM Page 557 558 Part IV ✦ Relational Data and XML Listing 21-13 (continued) strResults.append(“/>\r\n”); } }catch(Exception e) {} strResults.append(“</records>\r\n</resultset>”); System.out.println(strResults.toString()); return strResults.toString(); } Listing 21-14 shows what the Attribute XML output looks like for a quote in the application: Listing 21-14: Custom XML Output Generated by the GetSingleQuoteAttribute Class <?xml version=”1.0” encoding=”UTF-8”?> <resultset> <sql>SELECT dbo.Quotations.Quotation, dbo.Authors.AuthorName, dbo.Sources.[Source Name] FROM dbo.Quotations INNER JOIN dbo.Authors ON dbo.Quotations.AuthorID = dbo.Authors.AuthorID INNER JOIN dbo.Sources ON dbo.Quotations.SourceID = dbo.Sources.SourceID WHERE (dbo.Quotations.Quotation = ‘When the hurlyburlys done, When the battles lost and won.’) </sql> <metadata> <field name=”Quotation” datatype=”char”/> <field name=”AuthorName” datatype=”char”/> <field name=”Source Name” datatype=”char”/> </metadata> <records> <record rownumber=”1” Quotation=”When the hurlyburlys done, When the battles lost and won.” AuthorName=”Shakespeare, William” SourceName=”Macbeth”/> </records> </resultset> XML Servlets In general, Java has had some adoption issues in the IT marketplace, with the exception of Servlets. Java Applets have not lived up to the promise of universal, platform-independent application delivery using Web browsers as a front-end, i538292 ch21.qxd 8/18/03 8:44 AM Page 558 559 Chapter 21 ✦ Building XML-Based Web Applications with JDBC because of performance, reliability, and compatibility issues. Java Applications require a JDK or a JVM to be loaded on a client’s machine to provide any meaning- ful functionality, and unfortunately share the performance, reliability, and compati- bility characteristics of Java Applets. Servlets, however, are a different story. Java Servlets are quickly becoming the method of choice for implementing Java solu- tions in enterprise environments, mainly because of the high-performance Servlet Application servers on the market that support high-volume, high-capacity transac- tional Websites. Servlets are a natural fit for the middle tiers of multi-tier applica- tion architectures because of their relatively good security model and multi-thread performance characteristics. Because the Java in this case is running exclusively on a server, there are less performance, distribution, and compatibility issues than the Applet and Java Application Models. Servlets are Java Code that extends the HTTPServlet Java Class, which is the core of the Sun Java Servlet Development Kit (JSDK). Servlet class files are loaded onto a Servlet Application server and are called via Web browser requests. Every Servlet has a call method, which receives Servlet requests, and a response, which returns Servlet responses. Because of this structure and functionality, Servlets are a great tool for quickly and flexibly generating XML. We will provide some insight into how servlets work in this chapter as we go through the sample servlet code, but the chapter will focus more on XML than servlets. If you’re new to servlets and would like more information, the best place to start is the servlets.com Web page, at http://servlets.com. Also, Servlets are a Java Community Process (JCP) Specification. The latest Java Specification Request (JSR) document covers the Servlets 2.4 specification, and can be found at http://web1.jcp.org/en/jsr/detail?id=154. Example: A Three-Tier System Combining Java Applications, Servlets, and SQL Server In this section we’ll break up the Java Application that we showed you in Listings 21-1 to 21-14 and create two multi-tier servlet applications from the pieces. The first application is a Web browser implementation that provides an HTML inter- face to SQL Server data. The first tier is a Web browser, which provides the client user interface to the data. The second tier is made up of four Java Servlets that use JDBC to handle requests for data from the browser and retrieve data from the third tier, which is SQL Server and its associated databases. The Web application has a more basic user interface than the Java Application. The servlets are called via URLs from a Web page and response data is directed back to a browser window instead of a Java Application Object. The second application is a Java Application implementation that provides the same Swing and AWT interface to SQL Server data as the first application in this Note i538292 ch21.qxd 8/18/03 8:44 AM Page 559 560 Part IV ✦ Relational Data and XML chapter did. The difference this time is that the first tier is a Java Application that only handles the user interface. That means that you don’t need to load MS SQL Server JDBC drivers on the machine that is running the application. The JDBC drivers are used by the four application servlets on the second tier, so they only need to be loaded on the server. The third tier is SQL Server. Prerequisites for Servlet Development It probably goes without saying that multi-tier applications are harder to develop than single-tier applications. The biggest factor is all of the “moving parts.” You usu- ally need a client platform, one or more middle-tier platforms, and a server tier. Servlets run on a J2EE application server. Examples of J2EE application servers are IBM’s WebSphere application server, Bea WebLogic Application Server, Sun One Application Server, and Apache Tomcat. You’ll need one of these servers to use the example servlets in this chapter. The servlets need to be deployed onto the J2EE application server. Many J2EE IDEs come with an integrated J2EE Web application server that makes development, deployment, and testing of servlets much faster and easier. IDES with integrated J2EE servers include IBM’s WebSphere Studio Application Developer, and the Sun ONE Studio. Check your IDE documentation to see if it provides an integrated J2EE server for servlet development and testing. The application and servlets for this example were developed and tested using IBM’s WebSphere Studio Application Developer (WSAD) 5, which is available as a trial download from http://www7b.software.ibm.com/wsdd/zones/studio. WSAD includes an integrated J2EE application server, so servlets can be developed, tested, and deployed on the same machine. We are also running Microsoft SQL Server 2000 on the same machine with the JDBC driver loaded. WebSphere Studio Application Developer is discussed in more detail in Chapter 36. Introducing the XML example servlets and client application The following files are available for download from the XMLProgrammingBible.com Website. Check with the documentation of your J2EE server for instructions on deployment and setup. Check with your JDK setup instructions for information on running the Java client application on a client machine. All the servlets in this example, as well as the Java Application and T-SQL com- mands for producing the SQL Server data, can be downloaded from the XMLProgrammingBible.com Website, in the Downloads section. Cross- Reference i538292 ch21.qxd 8/18/03 8:44 AM Page 560 561 Chapter 21 ✦ Building XML-Based Web Applications with JDBC The Web example application in this chapter uses four servlets: ✦ XMLPBWebServletGetAuthorList gets a list of quote authors from the SQL Server Authors table. ✦ XMLPBWebServletGetSingleAuthorList gets a list of quotes for a single quote author that a user selects via a URL. ✦ XMLPBWebServletBuildElementXML returns a Quote in XML format with nested elements from row data to a Web browser. ✦ XMLPBWebServletBuildAttributeXML returns a Quote in XML format with attributes created from row data to a Web browser. The multi-tier Java Application uses four servlets and one client application: ✦ XMLPBAppServletGetAuthorList gets a list of quote authors from the SQL Server Authors table. ✦ XMLPBAppServletGetSingleAuthorList gets a list of quotes for a single quote author that a user selects in the Java Application. ✦ XMLPBAppServletBuildElementXML returns a Quote in XML format with nested elements from row data to the Java Application. ✦ XMLPBAppServletBuildAttributeXML returns a Quote in XML format with attributes created from row data to the Java Application. ✦ XMLPBServletApp is a Java Application that calls the above servlets to retrieve SQL Server data via JDBC. Running the Web Example Application Once the Web servlets have been deployed on a J2EE server, the MS SQL Server JDBC driver has been installed, and the JDBC driver is configured to access SQL Server data, start up any browser and open the following URL: http://<server IP address>/servlet/XMLPBWebServletGetAuthorList Most J2EE application servers are case sensitive. URLs must match file name and path case exactly. This is the first thing to check when having trouble with servlets in a Web browser environment. It may take 10-15 seconds for the Servlet to load the first time due to servlet initial- ization. If everything is configured properly, you should get results like those in Figure 21-2. The XMLPBWebServletGetAuthorList Servlet displays a unique list of quote authors, formatted as URL links. Caution i538292 ch21.qxd 8/18/03 8:44 AM Page 561 562 Part IV ✦ Relational Data and XML Figure 21-2: The output for the XMLPBWebServletGetAuthorList servlet, displaying a list of authors as links Clicking on one of the links calls the XMLPBWebServletGetSingleAuthorList Servlet that generates a list of quotes for a specific author. The author is deter- mined by a value that is passed in the link to the servlet. The links look like this to a Browser: <A HREF=/servlet/XMLPBWebServletGetSingleAuthorList?CategoryName=Dave+Barry >Dave Barry</A> Figure 21-3 shows the links for Dave Barry. Under each quote are two links, Element XML to Screen, and Attribute XML to Screen. The Element XML to Screen option calls the XMLPBWebServlet BuildElementXML Servlet to return the associated quote in a Custom XML Format. This is what the link looks like for the first Quote in Figure 21-3: <A HREF=/servlet/ XMLPBWebServletBuildElementXML?PassedQuote=There+is+a very+fine+line+between+hobby+and+mental+illness.>Element XML to Screen</A> i538292 ch21.qxd 8/18/03 8:44 AM Page 562 563 Chapter 21 ✦ Building XML-Based Web Applications with JDBC Figure 21-3: The output for the XMLPBWebServletGetSingleAuthorList Servlet, displaying a list of quotes for Dave Barry The Attribute XML to Screen option calls the XMLPBWebServletBuild AttributeXML Servlet to return the associated Quote in another form of custom XML format. Here’s what this link looks like: <A HREF=/servlet/ XMLPBWebServletBuildAttributeXML?PassedQuote=There+is+a very+fine+line+between+hobby+and+mental+illness.>Element XML to Screen</A> Removing spaces from parameters You may have noticed that the URL parameter references have a + where spaces usually are. When a value is passed as a parameter via HTTP, the parser in the application that receives the information stops at the first space it encounters, because it is expecting a constant stream of data, and a space indicates the end of a value. Therefore, spaces have to be removed from passed parameters. For example, Dave+Barry is received by a servlet as Dave+Barry and the spaces can be replaced using a simple one-line String.replace method in Java. However, Dave Barry (without the +) is parsed as just Dave, and will not match the correct value when re-sent as a parameter to a servlet. i538292 ch21.qxd 8/18/03 8:44 AM Page 563 [...]... (“jdbc:microsoft:sqlserver://1 27. 0.0.1:1433; User=jdbcUser;Password=jdbcUser; DatabaseName=XMLProgrammingBible”); Statement s = conn.createStatement(); Continued 573 574 Part IV ✦ Relational Data and XML Listing 21-18 (continued) ResultSet rs = s.executeQuery(sql); XMLDoc = buildAttributeXML(rs, sql); rs.close(); conn.close(); } catch(Exception e) { e.printStackTrace(); } return XMLDoc ; } String buildAttributeXML(ResultSet... ‘“+CategoryName+”’)”; The XMLPBWebServletBuildElementXML Servlet The code in Listing 21- 17 is called when a Quote is selected by clicking on the “Element XML to Screen” link from a Web browser Listing 21- 17: The XMLPBWebServletBuildElementXML Servlet Code import java.util.*; import java.io.*; import javax.servlet.*; Continued 569 570 Part IV ✦ Relational Data and XML Listing 21- 17 (continued) import javax.servlet.http.*;... strResults.toString(); } String entityRefs(String XMLString) { String[] before = {“&”,”\’”,”>”,””,” . { XMLString = stringReplace(XMLString, before[i], after[i]); } }else {XMLString=””;} return XMLString; } Continued i538292 ch21.qxd 8/18/03 8:44 AM Page 571 572 Part IV ✦ Relational Data and XML Listing. via a URL. ✦ XMLPBWebServletBuildElementXML returns a Quote in XML format with nested elements from row data to a Web browser. ✦ XMLPBWebServletBuildAttributeXML returns a Quote in XML format with attributes. Application. ✦ XMLPBAppServletBuildElementXML returns a Quote in XML format with nested elements from row data to the Java Application. ✦ XMLPBAppServletBuildAttributeXML returns a Quote in XML format

Ngày đăng: 09/08/2014, 18:22

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan