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

Web Server Programming phần 8 pot

63 236 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 63
Dung lượng 522,01 KB

Nội dung

System.out.println("The popular Java books:"); for(int i=0;i<bookNodes.getLength();i++) { Element bNode = (Element) bookNodes.item(i); NodeList temp = bNode.getElementsByTagName("STARS"); if(temp.getLength()==0)continue; // A book without a star rating Node starsNode = temp.item(0); String starCode = starsNode.getFirstChild().getNodeValue(); float stars = Float.parseFloat(starCode); if(stars<4.0) continue; Node titleNode = bNode.getElementsByTagName("TITLE").item(0); System.out.print(titleNode.getFirstChild().getNodeValue()); Node authorsNode = bNode.getElementsByTagName("AUTHORS").item(0); System.out.println("; " + authorsNode.getFirstChild().getNodeValue()); } If the XML document was to be checked for validity, a file with a DTD would have to be created; and a link to this DTD file would have to be set in the XML document file. The XML file would get a DOCTYPE link: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE LIST SYSTEM "books.dtd"> <LIST> <BOOK rank="1"> </BOOK> </LIST> The books.dtd file could contain the following: <! DTD for Books > <!ELEMENT LIST (BOOK)+> <!ELEMENT BOOK (ISBN, TITLE, AUTHORS, FORMAT?, STARS?, SHIPS?, LISTPRICE?, OURPRICE, SAVE?, USEDPRICE? )> <!ATTLIST BOOK rank CDATA #REQUIRED> <!ELEMENT ISBN (#PCDATA)> <!ATTLIST ISBN code CDATA #REQUIRED> <!ELEMENT TITLE (#PCDATA)> <!ELEMENT AUTHORS (#PCDATA)> <!ELEMENT FORMAT (#PCDATA)> <!ELEMENT STARS (#PCDATA)> <!ELEMENT SHIPS (#PCDATA)> DOM – the Document Object Model 427 <!ELEMENT LISTPRICE (#PCDATA)> <!ELEMENT OURPRICE (#PCDATA)> <!ELEMENT SAVE (#PCDATA)> <!ELEMENT USEDPRICE (#PCDATA)> Exercises Prac tical The servlet/JSP/XML exercises continue use of the Apache Tomcat engine as employed in the exercise for Chapters 7 and 8. Use the M3Gate phone emulator from http:// www.m3gate.com/ ; you can obtain alternative emulators from companies such as Nokia (see also the explorations exercise below). The XML parser exercises can be done with the xerces parser downloaded from http:/ /xml.apache.org/xerces2-j/index.html .Copyxerces.jar into the directory where you are developing an application and then specify a classpath like classpath=.:./ xerces.jar . (1) Implement a third version of the JSPs needed in the example web applicatio n fro m the exercise at the end of Chapter 8. This version is to have a modified Records class with an extra method that returns a java.lang.String that is an XML dump of the data in all the RequestData objects in its collection. The JSPs are to use XSL stylesheets to generate the required w eb pages with the data listings and the forms. These XML/XSL-based JSPs are simple: invoke XSLT processor using an XSL script ( request.xsl, review.xsl) applied to data obtained via the ‘get xml data’ method of the Records bean that is passed from servlet to JSP. The real code is in the two .xsl stylesheet files that you must create. Your WEB-INF directory will need to contains a tld subdirectory with the xsl.tld file, and a lib subdirectory with components like xerces.jar and xsl.jar. The JSPs will need directives like <%@ taglib uri="/xsltaglib" prefix="xsl" %>. (2) Implement a more complete version of the ‘pizza order’ example application that allows WAP-equipped customers to submit orders for customized pizzas via the web phones. (3) Build an application that combines: ● Static form pages. ● A control servlet. ● A bean that loads its data from database tables and which provides access to its data through a function that returns an XML document. ● A JSP that creates a response through the use of an XSL stylesheet that formats data from an XML document. 428 XML ● XSL stylesheets for generating both HTML and WML documents. The system is to allow students to obtain lecture details for chosen subjects. Queries may be submitted eith er via forms display ed on a web browser, or via a form displayed on a WAP-enabled phone. The system will respond with data for the subjects; the WAP-based display will, n aturally, show only a su bset of the data shown via a browser. The system should have the following components: ● Query.html, Query.wml These are static form entry pages for HTTP and WAP browsers. The form allows a user to select a discipline (from among a set of options in a select entry field), and a session of interest (again, picking an option – Autumn, Spring, Summer, Annual – from the options of a select). A d iscipline is something like Mathematics, IT, Computer Science, Biology, ; details of all subjects in that discipline should be retrieved. The form also includes a ‘Style’ parameter (as a hidden field in the H TML fo rm, an d as an extra postfield in the WML form); this parameter is included so that the JSP can select the appropriate docu - ment encoding and XSL stylesheet. ● NoData.html, NoData.wml These are static pages that are returned if there are no data th at satisfy a user’s request. ● LectureServlet This has a doPost() method that handles data from either the WML or HTML forms. The servlet should own a connection to a database (opened in its init() function and closed in its destroy() function). The doPost function extracts the discipline and session parameters and uses th ese to initialize an ‘ InfoBean’. The InfoBean is to search for data o n all subjects in the chosen discipline and session. The servlet should check whether any subject details were retrieved (e.g. a request for a Summer session Maths subject might fail to find any). If no subjects were found, the servlet should use response redirection to an appropriate error page ( NoData.html or NoData.wml). If the InfoBean found some subjects matching the chosen combination of discipline and session, the servlet will add the bean to the request as an extra attribute and forward the request to the JSP for final processing. ● Database The database has three tables. The first table lists all subject codes for each discipline: e.g. Mathematics/MATH101, Mathematics/MATH102, Biology/BIOL235. The second table contains data for a subject. The subject code acts as a primary key; other data include subject title, lecturer, session of offer, photo of lecturer (as a string field with the filename of the image; this file name can be placed as an <img > linkina returned HTML page), and a brief description of the subject contents. The third table contains lecture times. Each row has a subject code, a time string (con - tains day and time), a location string (lecture theater) and duration (hours of lecture). You will need to invent data to populate your tables. You need sufficient data so that there are subjects defined in at least two disciplines; on e discipline has more than one su b - ject in at least spring and autumn sessions, and these subjects have one or more lecture times allocated. (About 20 rows of data are needed in your three tables.) Exercises 429 ● InfoBean An InfoBean is created by the servlet, is used to retrieve data, and is passed to the JSP. The JSP w ill get its data fro m th e InfoBean as an XML string. The InfoBean will retrieve data by using the ‘discipline’ information to obtain a list of subject codes from the first table, retrieving each subject record from the second table and checking the session of offer, cre - ating a ‘Subject’ record for each subject offered in the desired discipline and session, and finally retrieving lecture times for the subject. (Several of these operations can be com - bined through the use of a more elaborate SQL query.) The bean will store these data in a vector. A getResults() function will create a strin g with its results represented in the form of an XML document with a DTD something like the following (there is no need to actually define a DTD and verify the documents): <!ELEMENT RESULTS (SUBJECT)+> <!ELEMENT SUBJECT (CODE, LECTURER, TITLE, PHOTO, ABSTRACT, LECTURE+)> <!ELEMENT CODE (#PCDATA)> <!ELEMENT TITLE (#PCDATA)> <!ELEMENT LECTURERE (#PCDATA)> <!ELEMENT PHOTO (#PCDATA)> <!ELEMENT ABSTRACT (#PCDATA)> <!ELEMENT LECTURE (TIME, LOCATION, DURATION)> <!ELEMENT TIME (#PCDATA)> <!ELEMENT LOCATION (#PCDATA)> <!ELEMENT DURATION (#PCDATA)> ● Java Server Page This will be a simple JSP that extracts the Style parameter from the request and uses this to set the document type and select a stylesheet. I t will then use XSL and the chosen stylesheet to format data obtained from the InfoBean that is passed as an attachment in the request context. ● WMLConvert.xsl, HTMLConvert.xsl These stylesh eets con tain XSL code for formatting data in the XML documen t from the InfoBean. The HTML stylesheet will generate a pag e that starts with a con tents section that is a list of intra-page links to sections for each subject. Each subject will have all data shown, with lecture times shown in a table. The WML stylesheet will g enerate a first card with a list of links to cards g enerated for each subject. Each subject card will show the subject title and lecture times. The following XML parsing exercises require an XML data file containing a reasonable amount of data (several hundred data items). This data file purportedly contains records of usage of resources at a web site (with the original data coming from an Apache log file). You can write a Java or Perl program to generate a suitable data file containing invented records. (If you did the Perl exercises that created a database of records from Apache log files, you could rework that program to generate a database with the required data, and then have a simple Perl or Ja va program that dumps the database contents as an XML file. 430 XML Some databases have an XML output feature that can generate such XML dumps automatically.) The XML file consists of a resourcelist element with several hundred resource ele - ments. Each resource is characterized by a name (supposedly the path name of a resource on the local web server) and two counts ( campus and remote) that record the number of requests for the resource from within the host domain and from sites external to the host domain. A resource also has a category attribute that distinguishes text files ( .html, .txt, .pdt), i mage s (.gif, .png), CGI programs/scripts, JSPs etc. The following fragment illustrates the fo rm of this XML document: <resourcelist> <resource category="text"> <name>/subjects/index.html</name> <campus>65</campus> <remote>52</remote> </resource> <resource category="image"> <name>/people/jkjones/jkj.jpg </name> <campus>22</campus> <remote>14</remote> </resource> <resource category="cgi"> <name>/cgi-bin/tutorials.cgi </name> <campus>24</campus> <remote>0</remote> </resource> </resourcelist> Two data analyses are to be performed. These are two be implemented as two SAX parser programs and then re-implemented using a DOM parser to create at tree represen - tation of the data that can then be traversed twice to extract the different information required. (4) Statistics This SAX program, or DOM program subtask, is to process the data in the XML file and extract the following information for both ‘text’ and ‘image’ data categories: ● Minimum usage ● Maximum usage ● Average usage ● Standard deviation in usage data Exercises 431 Separate statistical records are to be prepared for on ‘campus’ and ‘remote’ u sage. When all the data have been processed, the program is to produce a report similar to the following: Accesses to Text data On campus use: Minimum usage : 1 Maximum usage : 448 Average usage : 87 Standard deviation : 114.56 Remote use: Minimum usage : 1 Maximum usage : 2544 Average usage : 166 Standard deviation : 417.21 Accesses to Image data similar style of report (5) Usage analysis This program is to produce a report that identifies: ● The text file most frequently used from on campus. ● The text file most frequently used from off campus. ● a list o f all text files that are used significantly more frequently from o ff campus than from on campus (include files where more than 65 per cent of the total usage is from off campus); the listed data should show filename and on-campus and off-campus usage counts. Short answer questions (1) Explain the different approaches used by SAX and DOM parsers for XML documents. (2) Explain the structure of each ‘Element’ defined in the following DTD and the r esulting structure for a valid XML fragment. <!ELEMENT security-constraint (web-resource-collection+, auth-constraint?, user-data-constraint?)> <!ELEMENT web-resource-collection (web-resource-name, description?, url-pattern*, http-method*)> <!ELEMENT web-resource-name (#PCDATA)> 432 XML Explorations (1) Research and report on the existing services that deliver WWW-related content through to WAP phones. (2) The phone companies are suffering; their stock prices have slumped because they have spent too much on the purchase of radio spectrum slots for future g eneration phone ser - vices. They cry out for a killer application that will induce millions of customers to sub - stantially increase their mobile phone usage (and expenditure). Get some ideas by researching the proposals that have already been made for services delivered via WAP phones, come up with the killer application, and write a draft proposal that will attract start-up funding for your application. (3) Pick a business domain (finance, real estate, health care etc.) and research and report on the extent to which there has been agreement for standard XML documents for data interchange. (4) The original WAP/WML specifications make no provision for anything like ‘cookies’ thus limiting the range of applications to those that don’t require stateful sessions. There are proposals for adding equivalent mechanisms. Research these proposals and report on likely WAP extensions that will help support stateful sessions. (5) Research and write a short report on the different phone emulators that are available for testing WML applications. (6) Applications of XML include all kinds of mundane things, like defining software con- figurations, describing program structures, encoding remote procedure calls, repre- senting dumps of database tables and defining EDI formats. Get onto the WWW and discover and report on some of the more unexpected and esoteric applications of XML. (7) Research and report on the advantages of ‘schemas’ (as compared to older DTDs). (8) Research and report on the merits of the d ifferent XML parser implementations for Java (xerces is not the only parser library). (9) Many database systems now incorporate mechanisms for dumping the contents of tables, or the results of queries, as XML documents. Research and write a report on the extent of XML support in the database that you use (if it does not have XML support, pick something like SQLServer or Oracle). Exercises 433 This page intentionally left blank 10 Enterprise Java This chapter provides an introduction to Enterprise Java technologies. These technologies (and the somewhat comparable .NET technologies from Microsoft, see Appendix C) are aimed at ap plications th at are far mo re demandin g than the simple ‘web site w ith ord er form’-style applications reviewed in earlier chapters. These technologies support compo - nent-based approaches to the design, implementation and deployment of enterprise level applications; applications that typically involving inter-working of objects in different processes on different machines, and updates of multiple databases. The goal is to sim- plify the construction of distributed transactional applications, reducing d evelopment times and costs. Enterprise Java comprises a number of separate but interrelated Java technologies. You are somewhat familiar with four of them: Java Database Connectivity JDBC, Java Servlets, Java Server Pages, and Java-XML. Other Enterprise technologies include: ● JavaMail ● Java IDL and related support for CORBA – Common Object Request Br oker Architecture ● Enterprise JavaBeans (EJB) ● Java Messaging Services ● Java Transactions ● Java API for XML Processing ● Java Naming and Directory Interface (JNDI) The JavaMail API provides programmers with a convenient interface to the mail ser - vices supported by the operating system. It could be used in, for example, an application that relies o n email serv ices to ack nowledge orders submitted via th e web and then to pro - vide updates on the progress of the order. EJB and CORBA are both distributed object technologies. These technologies are used to build mu lti-tier client server systems. A typical th ree-tier system would have a Java client application, a middleware component that would either be a CORBA application or an EJB application, and a back-end database. Web-based clients would typically form part of a four-tier system. The browser-based client would work with a web server that would most likely use servlets. This web server would then work with the CORBA o r EJB engine; once again, there would be back-end database(s). Programs built using these tech - nologies involve communications among objects instantiated in different processes (it is similar to, though generally a little more complex than, Java RMI w hich you may have encountered previously). Ultimately, client and server objects communicate via messages transferred over TCP/IP networks. A major aim of the distributed object technologies is the concealment of this network layer. A client program (a Java client application, or a servlet in a web server) will make use of instances of proxy (stub) classes that have inter - faces that mimic those of the real server classes as instantiated in the EJB or CORBA engine. When an operation is invoked on a proxy, this object packages the request and uses low-level library components to transmit it to the server process. There the request is read, analyzed to identify the server object required, and converted into an invocation of the appropriate server operation. The server-side infrastructure code takes result data, packages them for transmission and sends them back to the client process. There the returned data are picked up by the proxy, allowing it to sustain the illusion that it did the work and is returning a result. Invocations on remote objects are synchronous; the client thread that invokes an operation on a proxy is blocked until the response is received. Java Messaging services support a different, asynchronous model for client–server relations among objects. Sometimes, it is more convenient for a client to package a request, and submit this package to a queuing system. Server processes will extract requests from this message queue, perform the work required, and queue responses. At some later time, a client will retrieve the response to its request. The EJB system has recently been extended so that it can be integrated with Messaging-style services. With JDBC, you can control the transactional character of operations that use a particular database connection. In more complex cases, tran sactions may involve multiple databases; such situations require more elaborate control mechanisms. The Java Transaction API pro- vides a high-level interface to services implemented using Java Transaction Services. The JTS layer is modeled on, and can interoperate with CO RBA transaction systems. The Java API for XML Processing (JAXP) is a second-generation version of Java classes for XML and is intended by Sun to become the standard for Java applications. It incorporates both SAX and DOM parsers, and also incorporates support for XSL stylesheet processing. The JNDI naming and directory components provide a uniform interface to many dif - ferent ‘naming services’, so simplifying the tasks of the developer. Naming services that are used by programs include DNS; COSNaming (a naming service used to obtain references to CORBA objects); the Lightweight Directory Access Protocol ( LDAP), which is a widely used directory service applied to things such maintaining lists of employees (an employee might have a name comprising person name, employment unit and department name); and NIS+, a naming service used on groups of Sun Solaris machines that enables the sharing of files and user accounts across those machines. All these services support some form of com - pound name; they vary in the nature of the components in the name and the rules for name construction. The JNDI interfaces try to conceal such differences of detail. If you are implementing a medium sized web-based application in Java, you should find that JDBC, servlets, JSP and a little XML to be quite sufficient. You move into the other areas of Enterprise Java only when attempting something much more ambitious. The scale 436 Enterprise Java [...]... of web server and application server may permit additional security controls; a first firewall can be used to protect the web server, and an additional firewall can protect the application server This increased protection is sometimes a motivating factor for the choice of EJB style rather than simpler servlet-and-bean style implementations If you are using Java application clients, rather than web. .. the web server that hosts servlets and JSPs The application.xml file describes the module structure; in this case, there are three modules (server, client and web client): ConverterApp Converter demo ejb-jar-ic.jar app-client-ic.jar war-ic.war< /web- uri>... helper classes used in the server process) Class declarations for the client classes and actual implementation class must of course match with respect to the defined public methods of the server (because otherwise the system will not be able to create appropriate Method objects) 10.2 EJB basics 10.2.1 Servers, containers and beans An EJB server will run as a process on your server machine It will host... request broker’ (ORB) components for client and for server, and naming services that help a client find a named server object Java RMI’s rmic is an example of a code generator; rmic takes information on a server class and generates the corresponding proxy class that will be used by clients Name servers include Java RMI’s rmiregistry, and CORBA COSNaming name servers An EJB system is similar is similar to... incorporates much of the same low-level code that would exist in a CORBA server (in fact, it may be the same code; some EJB vendors have built their products on top of existing CORBA servers) However, the EJB container extends the basic network-related code with additional code that supports certain common uses of server- side objects For example, server- side programs frequently need data bean objects – things... – represent a ‘business entity’, most often a block of data taken from a row in a relational table G Message beans – these allow an EJB server to act as a server for asynchronous message style client server systems Message beans are somewhat specialized; many EJB servers do not yet incorporate support for them Session beans should seem familiar to those who have worked with Java RMI or another comparable... deployer/administrator’ You have some experience with the role of web component creator’, having created web applications with static HTML files, JSPs, web. xml deployment files and servlets Apart from writing the code for the enterprise beans, an ‘enterprise bean author’ must also compose a deployment XML file This file, ejb-jar.xml, is considerably more complex than the web. xml files and is never composed by hand; instead,... on your following the naming conventions Finally, there are some unusual aspects to the way that server interfaces are defined in EJB Typically, as in RMI and CORBA, a server ‘interface’ is defined; this lists the public methods of the server class giving details of return and argument types and so forth A server class will implement this interface, as will the automatically generated client proxy (stub)... SimpleSavingsAccount"); SavingsAccountHome home = (SavingsAccountHome)PortableRemoteObject.narrow(objref, SavingsAccountHome.class); 4 58 Enterprise Java SavingsAccount duke = home.create("123", "Duke", "Earl", 0.00); duke.credit (88 .50); duke.remove(); SavingsAccount jones = home.findByPrimaryKey( "83 6"); jones.debit(2.00); Collection c = home.findByLastName("Smith"); Iterator i=c.iterator(); while (i.hasNext()) {... beans An EJB server will run as a process on your server machine It will host various ‘containers’ Containers can be web containers (for servlets), or EJB containers that hold enterprise beans Larger scale applications typically involve multiple EJB servers with one or more hosting web containers, and several others holding EJB containers The beans used in a single application may exist in different . back-end database. Web- based clients would typically form part of a four-tier system. The browser-based client would work with a web server that would most likely use servlets. This web server would. security-constraint (web- resource-collection+, auth-constraint?, user-data-constraint?)> <!ELEMENT web- resource-collection (web- resource-name, description?, url-pattern*, http-method*)> <!ELEMENT web- resource-name. transmit it to the server process. There the request is read, analyzed to identify the server object required, and converted into an invocation of the appropriate server operation. The server- side infrastructure

Ngày đăng: 14/08/2014, 12:20

TỪ KHÓA LIÊN QUAN