Kĩ thuật lập trình - Chương 28: Jax - Ws web services, web 2.0 and mash - ups

To add a Java DB database server in Netbeans Select Tools > Options to display the Netbeans Options dialog Click the Advanced Options button to display the Advanced Options dialog Under IDE Configuration, expand the Server and External Tool Settings node and select Java DB Database If the Java DB properties are not already configured, set the Java DB Location property to the location of Java DB on your system Set the Database Location property to the location where you’d like the Java DB databases to be stored

ppt114 trang | Chia sẻ: huyhoang44 | Lượt xem: 629 | Lượt tải: 0download
Bạn đang xem trước 20 trang tài liệu Kĩ thuật lập trình - Chương 28: Jax - Ws web services, web 2.0 and mash - ups, để xem tài liệu hoàn chỉnh bạn click vào nút DOWNLOAD ở trên
28JAX-WS Web Services, Web 2.0 and Mash-Ups1A client is tome a mere unit, a factor in a problem.Sir Arthur Conan DoyleThey also serve who only stand and wait.John Milton...if the simplest things of nature have a message that you understand, rejoice, for your soul is alive.Eleonora DuseProtocol is everything. Francoise Giuliani2OBJECTIVESIn this chapter you will learn: What a web service is.How to publish and consume web services in Netbeans.The elements that comprise web services, such as service descriptions and classes that implement web services.How to create client desktop and web applications that invoke web service methods.The important part that XML and the Simple Object Access Protocol (SOAP) play in enabling web services.How to use session tracking in web services to maintain client state information. How to use JDBC with web services to connect to databases. How to pass objects of user-defined types to and return them from a web service.328.1 Introduction 28.1.1 Downloading, Installing and Configuring Netbeans 5.5 and the Sun Java System Application Server 28.1.2 Web Services Resource Center and Java Resource Centers at www.deitel.com28.2 Java Web Services Basics28.3 Creating, Publishing, Testing and Describing a Web Service 28.3.1 Creating a Web Application Project and Adding a Web Service Class in Netbeans 28.3.2 Defining the HugeInteger Web Service in Netbeans4 28.3.3 Publishing the HugeInteger Web Service from Netbeans 28.3.4 Testing the HugeInteger Web Service with Sun Java System Application Server’s Tester Web Page 28.3.5 Describing a Web Service with the Web Service Description Language (WSDL)28.4 Consuming a Web Service 28.4.1 Creating a Client to Consume the HugeInteger Web Service 28.4.2 Consuming the HugeInteger Web Service28.5 SOAP528.6 Session Tracking in Web Services 28.6.1 Creating a Blackjack Web Service 28.6.2 Consuming the Blackjack Web Service28.7 Consuming a Database-Driven Web Service from a Web Application 28.7.1 Configuring Java DB in Netbeans and Creating the Reservation Database 28.7.2 Creating a Web Application to Interact with the Reservation Web Service28.8 Passing an Object of a User-Defined Type to a Web Service28.9 Wrap-Up28.10 Web Resources628.1 IntroductionWeb service A software component stored on one computer that can be accessed via method calls by an application (or other software component) on another computer over a network Web services communicate using such technologies as XML and HTTPSimple Object Access Protocol (SOAP) An XML-based protocol that allows web services and clients to communicate in a platform-independent manner728.1 IntroductionCompanies Amazon, Google, eBay, PayPal and many others make their server-side applications available to partners via web servicesBy using web services, companies can spend less time developing new applications and can create innovative new applicationsNetbeans 5.5 and Sun Java Studio Creator 2 enable programmers to “publish” and/or “consume” web services828.1.1 Downloading, Installing and Configuring Netbeans 5.5 and the Sun Java System Application ServerChapter uses Netbeans 5.5 and the Sun Java System Application Server with the default installation options Netbeans website provides a bundled installer for both www.netbeans.org/products/ide/Click the Download Netbeans IDE buttonDownload the installer with the title NetBeans IDE 5.5 with Java EE Application Server 9.0 U1 bundle928.1.2 Web Services Resource Center and Java Resource Centers at www.deitel.com Deitel Resource CentersWeb Services Resource Center www.deitel.com/WebServices/ Java Resource Centers www.deitel.com/java/www.deitel.com/JavaSE6/www.deitel.com/JavaEE5/1028.2 Java Web Services BasicsRemote machine or server The computer on which a web service resides A client application that accesses a web service sends a method call over a network to the remote machine, which processes the call and returns a response over the network to the applicationIn Java, a web service is implemented as a class that resides on a serverPublishing a web service Making a web service available to receive client requestsConsuming a web serviceUsing a web service from a client application1128.2 Java Web Services BasicsAn application that consumes a web service consists of two partsAn object of a proxy class for interacting with the web serviceA client application that consumes the web service by invoking methods on the proxy objectThe proxy object handles the details of communicating with the web service on the client’s behalfJAX-WS 2.0 Requests to and responses from web services are typically transmitted via SOAPAny client capable of generating and processing SOAP messages can interact with a web service, regardless of the language in which the web service is written 12Fig. 28.1 | Interaction between a web service client and a web service.1328.3 Creating, Publishing, Testing and Describing a Web ServiceHugeInteger web serviceProvides methods that take two “huge integers” (represented as Strings) Can determine their sum, their difference, which is larger, which is smaller or whether the two numbers are equal1428.3.1 Creating a Web Application Project and Adding a Web Service Class in NetbeansIn Netbeans, you focus on the logic of the web service and let the IDE handle the web service’s infrastructureTo create a web service in NetbeansCreate a project of type Web ApplicationThe IDE generates additional files that support the web application1528.3.2 Defining the HugeInteger Web Service in NetbeansEach new web service class created with the JAX-WS APIs is a POJO (plain old Java object)You do not need to extend a class or implement an interface to create a Web serviceWhen you compile a class that uses these JAX-WS 2.0 annotations, the compiler creates the compiled code framework that allows the web service to wait for and respond to client requests1628.3.2 Defining the HugeInteger Web Service in Netbeans@WebService annotation Indicates that a class represents a web serviceOptional element name specifies the name of the proxy class that will be generated for the clientOptional element serviceName specifies the name of the class that the client uses to obtain a proxy object. 1728.3.2 Defining the HugeInteger Web Service in NetbeansNetbeans places the @WebService annotation at the beginning of each new web service class you createYou can add the optional name and serviceName elements in the annotation’s parenthesesMethods that are tagged with the @WebMethod annotation can be called remotelyMethods that are not tagged with @WebMethod are not accessible to clients that consume the web service1828.3.2 Defining the HugeInteger Web Service in Netbeans@WebMethod annotation Optional operationName element to specify the method name that is exposed to the web service’s clientParameters of web methods are annotated with the @WebParam annotationOptional element name indicates the parameter name that is exposed to the web service’s clients19OutlineHugeInteger.java (1 of 6 ) Import the annotations used in this exampleIndicate that class HugeInteger is a web service20OutlineHugeInteger.java (2 of 6 ) 21OutlineHugeInteger.java (3 of 6 ) Declare that method add is a web method22OutlineHugeInteger.java (4 of 6 ) Declare that method subtract is a web method23OutlineHugeInteger.java (5 of 6 ) Declare that method bigger is a web method24OutlineHugeInteger.java (6 of 6 ) Declare that method smaller is a web methodDeclare that method equals is a web method25Common Programming Error 28.1 Failing to expose a method as a web method by declaring it with the @WebMethod annotation prevents clients of the web service from accessing the method. 26Common Programming Error 28.2 Methods with the @WebMethod annotation cannot be static. An object of the web service class must exist for a client to access the service’s web methods. 2728.3.3 Publishing the HugeInteger Web Service from NetbeansNetbeans handles all the details of building and deploying a web service for youIncludes creating the framework required to support the web serviceTo build projectRight click the project name in the Netbeans Projects tabSelect Build ProjectTo deploySelect Deploy Project Deploys to the server you selected during application setupAlso builds the project if it has changed and starts the application server if it is not already runningTo ExecuteSelect Run ProjectAlso builds the project if it has changed and starts the application server if it is not already runningTo ensure a clean re-build of the entire projectSelect Clean Project or Clean and Build Project 28Fig. 28.3 | Pop-up menu that appears when you right click a project name in the Netbeans Projects tab. 2928.3.4 Testing the HugeInteger Web Service with Sun Java System Application Server’s Tester Web pageSun Java System Application Server Can dynamically create a Tester web page for testing a web service’s methods from a web browserEnable this feature via the project’s Run optionsTo display the Tester web pageRun the web application from Netbeans, or Type web service’s URL in browser’s address field followed by ?TesterWeb server must be running for a client to access a web service If Netbeans launches the application server for you, the server will shut down when you close NetbeansTo keep it running, launch it independently of Netbeans30Fig. 28.4 | Tester web page created by Sun Java System Application Server for the HugeInteger web service. 31Fig. 28.5 | Testing HugeInteger’s add method. 3228.3.5 Describing a Web Service with the Web Service Description Language (WSDL)To consume a web serviceMust know where to find the web service Must be provided with the web service’s descriptionWeb Service Description Language (WSDL)Describe web services in a platform-independent mannerThe server generates a web service’s WSDL dynamically for you Client tools parse the WSDL to create the client-side proxy class that accesses the web serviceTo view the WSDL for a web serviceType URL in the browser’s address field followed by ?WSDL orClick the WSDL File link in the Sun Java System Application Server’s Tester web page3328.4 Consuming a Web ServiceWeb service client can be any type of application or even another web serviceWeb service reference Enables a client application to consume a web serviceDefines the client-side proxy class34Fig. 28.6 | A portion of the .wsdl file for the HugeInteger web service. 3528.4.1 Creating a Client in Netbeans to Consume the HugeInteger Web ServiceWhen you add a web service referenceIDE creates and compiles the client-side artifacts—the framework of Java code that supports the client-side proxy class Client calls methods on a proxy objectProxy uses client-side artifacts to interact with the web serviceTo add a web service referenceRight click the client project name in the Netbeans Projects tabSelect New > Web Service ClientSpecify the URL of the web service’s WSDL in the dialog’s WSDL URL field3628.4.1 Creating a Client in Netbeans to Consume the HugeInteger Web ServiceNetbeans uses the WSDL description to generate the client-side proxy class and artifactsNetbeans copies the web service’s WSDL into a file in your projectCan view this file from the Netbeans Files tabExpand the nodes in the project’s xml-resources folder. To update client-side artifacts and client’s WSDL copy Right click the web service’s node in the Netbeans Projects tab Select Refresh ClientTo view the IDE-generated client-side artifacts Select the Netbeans Files tab Expand the project’s build folder37Fig. 28.7 | New Web Service Client dialog. 38Fig. 28.8 | Netbeans Project tab after adding a web service reference to the project. 39Fig. 28.9 | Locating the HugeIntegerService.wsdl file in the Netbeans Files tab. 40Fig. 28.10 | Viewing the HugeInteger web service’s client-side artifacts generated by Netbeans. 4128.4.2 Consuming the HugeInteger Web Service42OutlineUsingHugeIntegerJFrame.java (1 of 10 ) Declare variables used to obtain and access the proxy object Obtain the proxy object 43OutlineUsingHugeIntegerJFrame.java (2 of 10 ) Use the proxy to invoke web method add 44OutlineUsingHugeIntegerJFrame.java (3 of 10 ) Use the proxy to invoke web method subtract 45OutlineUsingHugeIntegerJFrame.java (4 of 10 ) Use the proxy to invoke web method bigger 46OutlineUsingHugeIntegerJFrame.java (5 of 10 ) Use the proxy to invoke web method smaller 47OutlineUsingHugeIntegerJFrame.java (6 of 10 ) Use the proxy to invoke web method equals 48OutlineUsingHugeIntegerJFrame.java (7 of 10 ) 49OutlineUsingHugeIntegerJFrame.java (8 of 10 ) 50OutlineUsingHugeIntegerJFrame.java (9 of 10 ) 51OutlineUsingHugeIntegerJFrame.java (10 of 10 ) 5228.5 SOAPSOAP (Simple Object Access Protocol)Commonly used, platform-independent, XML-based protocol that facilitates remote procedure calls, typically over HTTPWire format or wire protocolProtocol that transmits request-and-response messages Defines how information is sent “along the wire” SOAP message (also known as a SOAP envelope) Each request and response is packaged in a SOAP message Contains information that a web service requires to process the message5328.5 SOAPWire format must support all types passed between the applicationsSOAP supports Primitive types and their wrapper typesDate, Time and othersCan also transmit arrays and objects of user-defined typesRequest SOAP message’s contentsMethod to invoke Method’s arguments Response SOAP message’s contentsResult of method callClient-side proxy parses the response and returns the result to the client applicationSOAP messages are generated for you automatically54Fig. 28.12 | SOAP messages for the HugeInteger web service’s add method as shown by the Sun Java System Application Server’s Tester web page. 5528.6 Session Tracking in Web ServicesIt can be beneficial for a web service to maintain client state informationEliminates the need to pass client information between the client and the web service multiple timesEnables a web service to distinguish between clients5628.6.1 Creating a Blackjack Web ServiceTo use session tracking in a Web serviceMust include code for the resources that maintain the session state informationJAX-WS handles this for you via the @Resource annotationEnables tools like Netbeans to “inject” complex support code into your classYou focus on business logic rather than support codeUsing annotations to add code is known as dependency injectionAnnotations like @WebService, @WebMethod and @WebParam also perform dependency injection5728.6.1 Creating a Blackjack Web ServiceWebServiceContext object Enables a web service to access and maintain information for a specific request, such as session state@Resource annotation injects the code that creates a WebServiceContext object MessageContext objectObtained from WebServiceContext object MessageContext object’s get method returns HttpSession object for the current clientReceives a constant indicating what to get from the MessageContextMessageContext.SERVLET_REQUEST indicates that we’d like to get the HttpServletRequest object Can then call HttpServletRequest method getSession to get the HttpSession objectHttpSession method getAttribute Receives a String that identifies the Object to obtain from the session state58OutlineBlackjack.java (1 of 4 ) Import classes used for session handling Inject code to create the WebServiceContext object59OutlineBlackjack.java (2 of 4 ) Get an ArrayList of Strings representing the current client’s deck from the session objectGet the MessageContext and use it to obtain the HttpSession object for the current client 60OutlineBlackjack.java (3 of 4 ) Place the deck in the session object61OutlineBlackjack.java (4 of 4 ) 6228.6.2 Consuming the Blackjack Web ServiceIn JAX-WS 2.0 Client must indicate whether it wants to allow the web service to maintain session informationCast the proxy object to interface type BindingProviderEnables the client to manipulate the request information that will be sent to the serverInformation is stored in an object that implements interface RequestContextBindingProvider and RequestContext are created by the IDE when you add a web service client to the application Invoke the BindingProvider’s getRequestContext method to obtain the RequestContext objectCall the RequestContext’s put method to set the property BindingProvider.SESSION_MAINTAIN_PROPERTY to trueEnables session tracking from the client side so that the web service knows which client is invoking the service’s web methods63OutlineBlackjackGameJ Frame.java (1 of 18 ) Used to enable session tracking from the client application64OutlineBlackjackGameJ Frame.java (2 of 18 ) Enable session tracking for the client 65OutlineBlackjackGameJ Frame.java (3 of 18 ) 66OutlineBlackjackGameJ Frame.java (4 of 18 ) 67OutlineBlackjackGameJ Frame.java (5 of 18 ) 68OutlineBlackjackGameJ Frame.java (6 of 18 ) 69OutlineBlackjackGameJ Frame.java (7 of 18 ) 70OutlineBlackjackGameJ Frame.java (8 of 18 ) 71OutlineBlackjackGameJ Frame.java (9 of 18 ) 72OutlineBlackjackGameJ Frame.java (10 of 18 ) 73OutlineBlackjackGameJ Frame.java (11 of 18 ) 74OutlineBlackjackGameJ Frame.java (12 of 18 ) 75OutlineBlackjackGameJ Frame.java (13 of 18 ) 76OutlineBlackjackGameJ Frame.java (14 of 18 ) 77OutlineBlackjackGameJ Frame.java (15 of 18 ) 78OutlineBlackjackGameJ Frame.java (16 of 18 ) 79OutlineBlackjackGameJ Frame.java (17 of 18 ) 80OutlineBlackjackGameJ Frame.java (18 of 18 ) 8128.7 Consuming a Database-Driven Web Service from a Web Application Because web-based businesses are becoming increasingly prevalent, it is common for web applications to consume web services8228.7.1 Configuring Java DB in Netbeans and Creating the Reservation DatabaseTo add a Java DB database server in NetbeansSelect Tools > Options to display the Netbeans Options dialogClick the Advanced Options button to display the Advanced Options dialogUnder IDE Configuration, expand the Server and External Tool Settings node and select Java DB DatabaseIf the Java DB properties are not already configured, set the Java DB Location property to the location of Java DB on your systemSet the Database Location property to the location where you’d like the Java DB databases to be stored8328.7.1 Configuring Java DB in Netbeans and Creating the Reservation DatabaseTo create a new databaseSelect Tools > Java DB Database > Create Java DB Database Enter the name of the database to create, a username and a passwordClick OK to create the databaseCan use the Netbeans Runtime tab to create tables and to execute SQL statements that populate the database with dataClick the Netbeans Runtime tab and expand the Databases node. Netbeans must be connected to the database to execute SQL statementsIf not connected, right click the icon next to the databse and click Connect84Fig. 28.15 | Seats table configuration. 85Fig. 28.16 | Seats table’s data. 86OutlineReservation.java (1 of 3 ) Import classes and interfaces used for database processingStrings that represent the database URL, username and password87OutlineReservation.java (2 of 3 ) Get a connection to the database Create a Statement for executing queriesExecute a query that selects seats that are not taken and match the specified criteria Update a seat as taken88OutlineReservation.java (3 of 3 ) 8928.7.2 Creating a Web Application to Interact with the Reservation Web ServiceTo add a web service to a web application in Java Studio Creator 2 Click the Add Web Service button Specify the web service’s WSDL in the dialog that appears90OutlineReserve.jsp (1 of 4 ) 91OutlineReserve.jsp (2 of 4 ) 92OutlineReserve.jsp (3 of 4 ) 93OutlineReserve.jsp (4 of 4 ) 94OutlineReserve.java (1 of 4 ) 95OutlineReserve.java (2 of 4 ) 96OutlineReserve.java (3 of 4 ) 97OutlineReserve.java (4 of 4 ) Store selected seat type in the session bean Store selected class type in the session bean 9828.8 Passing an Object of a User-Defined Type to a Web ServiceWeb services can receive and return objects of user-defined types—known as custom types. Custom types that are sent to or from a web service using SOAP are serialized into XML formatThis process is referred to as XML serializationHandled for you automaticallyCustom typeIf used to specify parameter or return types in web methods, must provide a public default or no-argument constructorAny instance variables that should be serialized must have public set and get methods or the instance variables must be declared publicAny instance variable that is not serialized simply receives its default value when an object of the class is deserialized99Common Programming Error 28.3 A runtime error occurs if an attempt is made to deserialize an object of a class that does not have a default or no-argument constructor. 100OutlineEquation.java (1 of 4 ) Set and get methods are provided for these instance variables so they can be XML serializedRequired constructor because objects of this class are passed to or returned from web methods101OutlineEquation.java (2 of 4 ) 102OutlineEquation.java (3 of 4 ) 103OutlineEquation.java (4 of 4 ) 104OutlineGenerator.java (1 of 2 ) 105OutlineGenerator.java (2 of 2 ) Note that no special code is required to return an object of our user-defined class from the web method106Fig. 28.22 | Testing a web method that returns an XML serialized Equation object. (Part 1 of 2.) 107Fig. 28.22 | Testing a web method that returns an XML serialized Equation object. (Part 2 of 2.) 108OutlineEquationGenerator ClientJFrame.java (1 of 6 ) 109OutlineEquationGenerator ClientJFrame.java (2 of 6 ) 110OutlineEquationGenerator ClientJFrame.java (3 of 6 ) 111OutlineEquationGenerator ClientJFrame.java (4 of 6 ) Note that no special code is required to receive an object of our user-defined class from the web method112OutlineEquationGenerator ClientJFrame.java (5 of 6 ) 113OutlineEquationGenerator ClientJFrame.java (6 of 6 ) 114

Các file đính kèm theo tài liệu này:

  • pptjavahtp7e_28_1417_238.ppt