Baixe Capítulo 41 - Servicios Web - Liang-Java-Comp11e e outras Resumos em PDF para Informática, somente na Docsity!
Objectives
■ ■ To describe what a Web service is (§41.1).
■ ■ To create a Web service class (§41.2).
■ ■ To publish and test a Web service (§41.3).
■ ■ To create a Web service client reference (§41.4).
■ ■ To explain the role of WSDL (§41.4).
■ ■ To pass arguments of object type in a Web service (§41.5).
■ ■ To discover how a client communicates with a Web service (§41.5).
■ ■ To describe what SOAP requests and SOAP responses are (§41.5).
■ ■ To track a session in Web services (§41.6).
Web Services
CHAPTER
41-2 Chapter 41 Web Services
41.1 Introduction
Web services is about sharing objects on the Internet.
Web service is a technology that enables programs to communicate through HTTP on the
Internet. Web services enable a program on one system to invoke a method in an object on
another system. You can develop and use Web services using any languages on any platform.
Web services are simple and easy to develop.
Web services run on the Web using HTTP. There are several APIs for Web services. A
popular standard is the Simple Object Access Protocol (SOAP), which is based on XML. The
computer on which a Web service resides is referred to as a server. The server needs to make
the service available to the client, known as publishing a Web service. Using a Web service
from a client is known as consuming a Web service.
A client interacts with a Web service through a proxy object. The proxy object facilitates the
communication between the client and the Web service. The client passes arguments to invoke
methods on the proxy object. The proxy object sends the request to the server and receives the
result back from the server, as shown in Figure 41.1.
Figure 41.1 A proxy object serves as a facilitator between a client and a Web service.
Client
Web service proxy object
Server
Web Internet service
Point
Key
41.1.1 What is a Web service? 41.1.2 Can you invoke a Web service from a language other than Java? 41.1.3 Do Web services support callback? That is, can a Web service call a method from
a client’s program?
41.1.4 What is SOAP? What is it to publish a Web service? What is it to consume a Web
service? What is the role of a proxy object?
41.2 Creating Web Services
An IDE such as NetBeans is an effective tool for developing and deploying
Web services.
There are many tools for creating Web services. This book demonstrates creating Web services
using NetBeans.
Note Apache Tomcat Server does not work well with Web services. To develop and deploy Web services using NetBeans, you need to install GlassFish. For information on how to install GlassFish on NetBeans.
We now create a Web service for obtaining student scores. A Web service is a class that
contains the methods for the client to invoke. Name the class ScoreService with a method
named findScore(String name) that returns the score for a student.
First, you need to create a Web project using the following steps:
1. Choose File, New Project to display the New Project dialog box. In the New Project
dialog box, choose Java Web in the Categories pane and choose Web Application in
the Projects pane. Click Next to display the New Web Application dialog box.
Point
Check
Point
Key
41-4 Chapter 41 Web Services
The annotation (line 19)
@WebMethod(operationName = "findScore")
indicates that findScore is a method that can be invoked from a client.
The findScore method returns a score if the name is in the hash map. Otherwise, it returns
You can manually type the code for the service, or create it from the Design tab, as shown
in Figure 41.2.
Figure 41.2 The services can also be created from the Design pane.
41.3 Deploying and Testing Web Services
Deploying a Web service is to make it available on the Internet for other programs
to use.
After a Web service is created, you need to deploy it for clients to use. Deploying Web services
is also known as publishing Web services. To deploy it, right-click the WebServiceProject
in the Project to display a context menu and choose Deploy. This command will first undeploy
the service if it was deployed and then redeploy it.
Now you can test the Web service by entering the follow URL in a browser, as shown in
Figure 41.3.
http://localhost:8080/WebServiceProject/ScoreWebService?Tester
Note ScoreWebService is the name you specified in line 7 in Listing 41.1. This Web
service has only one remote method named findScore. You can define an unlimited number
of remote methods in a Web service class. If so, all these methods will be displayed in the
test page.
To test the findScore method, enter Michael and click the findScore button. You will
see that the method returns 100.0 , as shown in Figure 41.4.
Point
Key
41.3 Deploying and Testing Web Services 41-
Note If your computer is connected to the Internet, you can test Web services from another computer by entering the following URL:
http://host:8080/WebServiceProject/ScoreWebService?Tester
Where host is the host name or IP address of the server on which the Web service is run- ning. On Windows, you can find your IP address by typing the command ipconfig.
Note If you are running the server on Windows, the firewall may prevent remote clients from accessing the service. To enable it, do the following:
- In the Windows control panel, click Windows Firewall to display the Windows Firewall dialog box.
Figure 41.3 The test page enables you to test Web services.
Figure 41.4 The method returns a test value.
41.4 Consuming Web Services 41-
Note When you created a Web service reference, you entered a WSDL URL, as shown in Figure 41.6. This creates a .wsdl file. In this case, it is named ScoreWebService.wsdl under the Web Service References folder, as shown in Figure 41.8. So what is WSDL? WSDL stands for Web Service Description Language. A .wsdl file is an XML file that describes the available Web service to the client—i.e., the remote methods, their param- eters and return value types, and so on.
Note If the Web service is modified, you need to refresh the reference for the client. To do so, right-click the Web service node under Web Service References to display a context menu and choose Refresh Client.
Now you are ready to create a client for the Web service. Right-click the ScoreWebService
ClientProject node in the Project pane to display a context menu, and choose New, Class
to create a Java client named FindScoreApp in package chapter41 , as shown in Listing 41.2.
Figure 41.6 The New Web Service Client dialog box creates a Web service reference.
Figure 41.7 You can see the automatically generated boilerplate code for Web services in
the Generated Sources folder in the client’s project.
41-8 Chapter 41 Web Services
Listing 41.2 FindScoreApp.java
1 package chapter41; 2 3 import javafx.application.Application; 4 import javafx.scene.Scene; 5 import javafx.scene.control.Button; 6 import javafx.scene.control.Label; 7 import javafx.scene.control.TextField; 8 import javafx.scene.layout.GridPane; 9 import javafx.stage.Stage; 10 import myWebservice.ScoreWebService; 11 import myWebservice.ScoreService; 12 13 public class FindScoreApp extends Application { 14 // Declare a service object and a proxy object 15 private ScoreWebService scoreWebService = new ScoreWebService(); 16 private ScoreService proxy 17 = scoreWebService.getScoreServicePort(); 18 19 private Button btGetScore = new Button( "Get Score" ); 20 private TextField tfName = new TextField(); 21 private TextField tfScore = new TextField(); 22 23 public void start(Stage primaryStage) { 24 GridPane gridPane = new GridPane(); 25 gridPane.setHgap( 5 ); 26 gridPane.add( new Label( "Name" ), 0 , 0 ); 27 gridPane.add( new Label( "Score" ), 0 , 1 ); 28 gridPane.add(tfName, 1 , 0 ); 29 gridPane.add(tfScore, 1 , 1 ); 30 gridPane.add(btGetScore, 1 , 2 ); 31 32 // Create a scene and place the pane in the stage 33 Scene scene = new Scene(gridPane, 250 , 250 ); 34 primaryStage.setTitle( "FindScoreApp" ); // Set the stage title 35 primaryStage.setScene(scene); // Place the scene in the stage 36 primaryStage.show(); // Display the stage 37
Figure 41.8 The .wsdl file describes Web services to clients.
41-10 Chapter 41 Web Services
The proxy object receives the SOAP response from the Web service and parses it. This
process is illustrated in Figure 41.10.
Can you pass an argument of any type between a client and a Web service? No.
SOAP supports only primitive types, wrapper types, arrays, String , Date , Time , List ,
and several other types. It also supports certain custom classes. An object that is sent to or
from a server is serialized into XML. The process of serializing/deserializing objects, called
Figure 41.9 The client request and server response are described in XML.
41.5 Passing and Returning Arguments 41-
XML serialization/deserialization , is performed automatically. For a custom class to be used
with Web methods, the class must meet the following requirements:
1. The class must have a no-arg constructor.
2. Instance variables that should be serialized must have public get and set methods. The
classes of these variables must be supported by SOAP.
To demonstrate how to pass an object argument of a custom class, Listing 41.3 defines a Web
service class named AddressService with two remote methods:
■ ■ getAddress(String firstName, String lastName) that returns an Address
object for the specified firstName and lastName.
■ ■ storeAddress(Address address) that stores a Student object to the database.
Address information is stored in a table named Address in the database. The Address class
was defined in Listing 42.12, Address.java. An Address object can be passed to or returned
from a remote method, since the Address class has a no-arg constructor with get and set
methods for all its properties.
Here are the steps to create a Web service named AddressService and the Address
class in the project.
1. Right-click the WebServiceProject node in the project pane to display a context
menu. Choose New, Web Service to display the New Web Service dialog box.
2. In the Web Service Name field, enter AddressService. In the Package field, enter
chapter41. Click Finish to create the service class.
3. Right-click the WebServiceProject node in the project pane to display a context
menu. Choose New, Java Class to display the New Java Class dialog box.
4. In the Class Name field, enter Address. In the Package field, enter chapter37. Click
Finish to create the class.
The Address class is the same as shown in Listing 37.12. Complete the AddressService
class as shown in Listing 41.3.
Listing 41.3 AddressService.java
1 package chapter41; 2 3 import chapter37.Address; 4 import java.sql.*; 5 import javax.jws.WebMethod; 6 import javax.jws.WebService; 7 8 @WebService(name = "AddressService", 9 serviceName = "AddressWebService")
Figure 41.10 A proxy object sends SOAP requests and receives SOAP responses.
Client
Web service proxy object
Server
SOAP Response
SOAP Request Web service
41.5 Passing and Returning Arguments 41-
69 try { 70 Class .forName( "com.mysql.jdbc.Driver" ); 71 72 // Connect to the sample database 73 Connection connection = DriverManager.getConnection( 74 "jdbc:mysql://localhost/javabook", "scott", "tiger" ); 75 76 statement1 = connection.prepareStatement( 77 "select * from Address where firstName =? and lastName = ?" ); 78 statement2 = connection.prepareStatement( 79 "insert into Address " + 80 "(lastName, firstName, mi, telephone, email, street, city, " 81 + "state, zip) values (?, ?, ?, ?, ?, ?, ?, ?, ?)" ); 82 } catch (Exception ex) { 83 ex.printStackTrace(); 84 } 85 } 86 }
The new Web service is named AddressWebService (line 9) for the AddressService
class.
When the service is deployed, the constructor (lines 17–19) of AddressWebService is
invoked to initialize a database connection and create prepared statement1 and statement
(lines 68–85).
The findAddress method searches the address in the Address table for the specified
firstName and lastName. If found, the address information is returned in an Address object
(lines 29–38). Otherwise, the method returns null (line 41).
The storeAddress method stores the address information from the Address object into
the database (lines 52–61).
Note Don’t forget that you have to add the MySQL library to the WebServiceProject for this example to run.
Before you can use the service, deploy it. Right-click the WebServiceProject node in the
Project to display a context menu and choose Deploy.
Now you are ready to develop a Web client that uses the AddressWebService. The
client is a JSP program, as shown in Figure 41.11. The program has two functions. First,
the user can enter the last name and first name and click the Search button to search for a
record, as shown in Figure 41.12. Second, the user can enter the complete address infor-
mation and click the Store button to store the information to the database, as shown in
Figure 41.13.
Let us create a project for the client. The project named AddressWebServiceClient
Project can be created as follows:
1. Choose File, New Project to display the New Web Application dialog box. In the
New Web Application dialog box, choose Java Web in the Categories pane and choose
Web Application in the Projects pane. Click Next to display the Name and Location
dialog box.
2. Enter AddressWebServiceClientProject as the project name, specify the location
where you want the project to be stored, and uncheck the Set as Main Project check box.
Click Next to display the Server and Settings dialog box.
3. Choose GlassFish Server 4 in the Server field, and Java EE 7 Web as in the Java
EE Version field, and click Finish to create the project.
41-14 Chapter 41 Web Services
Figure 41.12 The Search button finds and displays an address.
Figure 41.13 The Store button stores the address to the database.
Figure 41.11 The TestAddressWebService page allows the user to search and store
addresses.
41-16 Chapter 41 Web Services
9 **** 10 **** 11 **** Address Information **** 12 **** 13 **** 14 **** 15 Last Name **** * **** 16 **** 19 size = "20" /> 20 21 First Name **** * **** 22 **** 25 size = "20" /> 26 27 MI 28 **** 31 size = "3" /> 32 33 Telephone 34 **** 37 size = "20" /> 38 39 Email 40 **** 43 size = "28" /> 44
45 46
Street 47 **** 50
size =
"50" /> 51
52 53
City 54 **** 57
size =
"23" /> 58 59 State 60 **** 61 **** 62 **** 63 **** 64 **** 65 66 Zip 67 ****
41.6 Web Service Session Tracking **41-**
70 size = "9" /> 71
72 73
74 **** 75 **** 76
77 **** 78
* required fields
79 80
<% 81
if (request.getParameter(
"Submit" ) !=
null ) { 82 AddressWebService addressWebService =
new AddressWebService(); 83 AddressService proxy = addressWebService.getAddressServicePort(); 84 85
if (request.getParameter(
"Submit" ).equals(
"Store" )) { 86 proxy.storeAddress(addressId); 87 out.println(addressId.getFirstName() +
" " + 88 addressId.getLastName() +
" has been added to the database" ); 89 } 90
else if (request.getParameter(
"Submit" ).equals(
"Search" )) { 91 Address address = proxy.getAddress(addressId.getFirstName(), 92 addressId.getLastName()); 93
if (address ==
null ) 94 out.print(addressId.getFirstName() +
" " + 95 addressId.getLastName() +
" is not in the database" ); 96
else 97 addressId = address; 98 } 99 } 100
%> 101 **** 102 ****
Lines 2–4 import the classes for the JSP page. The Address class (line 2) was created in
the WebServiceProject and was automatically copied to the AddressWebService
ClientProject project when a Web service reference for AddressWebService was created.
A JavaBeans object for Address was created and associated with input parameters in lines 5–7.
The UI interface was laid in the form (lines 14–77). The action for the two buttons Search
and Store invokes the same page TestAddressWebService.jsp (line 14).
When a button is clicked, a proxy object for AddressWebService is obtained (lines
82–83). For the Store button, the proxy object invokes the storeAddress method to add an
address to the database (line 86). For the Search button, the proxy object invokes the getAd
dress method to return an address (lines 91–92). If no address is found for the specified first
and last names, the returned address is null (line 93).
41.6 Web Service Session Tracking
You can use the HttpSession interface to session tracking for Web.
Section 37.8.3, Session Tracking Using the Servlet API, introduced session tracking for servlets
using the javax.servlet.http.HttpSession interface. You can use HttpSession to
implement session tracking for Web services. To demonstrate this, consider an example that
generates random True/False questions for the client and grades the answers on these ques-
tions for the client.
The Web client consists of two JSP pages: DisplayQuiz.jsp and GradeQuiz.jsp. The
DisplayQuiz page invokes the service method getQuestion() to display the questions,
as shown in Figure 41.15. When you click the Submit button, the program invokes the service
Point
Key
41.6 Web Service Session Tracking 41-
22 quiz.add( new Object[]{ 23 "Is New Orleans the capital of Louisiana?" , false }); 24 quiz.add( new Object[]{ 25 "Is Chicago the capital of Illinois?" , false }); 26 27 // Shuffle to generate a random quiz for a client 28 java.util.Collections.shuffle(quiz); 29 } 30 31 @WebMethod(operationName = "getQuestions" ) 32 public java.util.List getQuestions() { 33 34 // Extract questions from quiz 35 List questions = new ArrayList(); 36 for ( int i = 0 ; i < quiz.size(); i++) { 37 questions.add((String)(quiz.get(i)[0])); 38 } 39 40 return questions; // Return questions in the quiz 41 } 42 43 @WebMethod(operationName = "gradeQuiz" ) 44 public List gradeQuiz(List answers) { 45 List result = new ArrayList(); 46 for ( int i = 0 ; i < quiz.size(); i++) 47 result.add(quiz.get(i)[ 1 ] == answers.get(i)); 48 49 return result; 50 } 51 }
The Web service class named QuizService contains two methods getQuestions and
gradeQuiz. The new Web service is named QuizWebService (line 10).
The annotation @HttpSessionScope (line 9) is new in JAX-WS 2.2, which enables the
Web service automatically maintains a separate instance for each client session. To use this
annotation, you have add JAX-WS 2.2 into your project’s library. This can be done by clicking
the Library node in the project and select Add Library.
Assume five True/False questions are available from the service. The quiz is stored in an
ArrayList (lines 16–25).
Each element in the list is an array with two values. The first value is a string that describes
the question and the second is a Boolean value indicating whether the answer should be true
or false.
A new quiz is generated in the constructor and the quiz is shuffled using the shuffle method
in the Collections class (line 28).
The getQuestions method (lines 31–40) returns questions in a list. The questions are
extracted from the quiz (lines 34–37) and are returned (line 39).
The gradeQuiz method (lines 42–49) checks the answers from the client with the answers
in the quiz. The client’s answers are compared with the key, and the result of the grading is
stored in a list. Each element in the list is a Boolean value that indicates whether the answer
is correct or incorrect (lines 44–46).
After creating and publishing the Web service, let us create a project for the client. The
project named QuizWebServiceClientProject can be created as follows:
1. Choose File, New Project to display the New Web Application dialog box.
2. In the New Web Application dialog box, choose Java Web in the Categories pane and
choose Web Application in the Projects pane. Click Next to display the Name and
Location dialog box.
41-20 Chapter 41 Web Services
3. Enter QuizWebServiceClientProject as the project name, specify the location
where you want the project to be stored, and uncheck the Set as Main Project check
box. Click Next to display the Server and Settings dialog box.
4. Choose GlassFish Server 4 in the Server field, and Java EE 7 Web as in the Java
EE Version field, and click Finish to create the project.
To use QuizWebService , you need to create a Web service client as follows:
1. Right-click the QuizWebServiceClientProject project in the Project pane to display
a context menu. Choose New, Web Service Client to display the New Web Service
Client dialog box.
2. Check the WSDL URL radio button and enter http://localhost:8080/WebServiceProject/
QuizWebService?WSDL in the WSDL URL field.
3. Enter myWebservice in the Package field. Click Finish to create the reference for
QuizWebService.
Now a reference to QuizWebService is created. You can create a proxy object to access the
remote methods in QuizService. Listings 41.6 and 41.7 show DisplayQuiz.jsp and Grad-
eQuiz.jsp.
Listing 41.6 DisplayQuiz.jsp 1 2 <%@ page import = "myWebservice.QuizWebService" %> 3 <%@ page import = "myWebservice.QuizService" %> 4 ** 6 **** 7 8 **** 9 **** 10 <% 11 QuizService proxy = quizWebService.getQuizServicePort(); 12 java.util.List questions = 13 (java.util.ArrayList)(proxy.getQuestions()); 14 %> 15 ** 16 **** 17 <% for ( int i = 0 ; i < questions.size(); i++) { %> 18 **** 19 **** 20 <%= questions.get(i) %> 21 **** 22 **** 23 **** 24 value = "True" /> True 25 **** 26 **** 27 **** 28 value = "False" /> False 29 **** 30 **** 31 <%}%> 32 **** 33 **
34 **