Chapter 8 JAX-WS Web Services 8.1. Introduction to Web Services by yaosaigeng


									                            Chapter 8 JAX-WS Web Services

8.1. Introduction to Web Services

8.2. WSDL

8.3. SOAP

8.4 Your First Web Service

8.5 Accessing Web Services

8.6 Web Services, Session Beans, and State

8.7 RESTful Web Services

8.8 Practice Labs

8.9 Summary

8.10 Chapter Review

8.11 Exercises

In This Chapter:

JAX-WS     Web Services



Accessing   Web Services

REST/RESTful       Web Service Concepts

Practice   Labs
8.1 Introduction to Web Services

       What is a web service? If you asked some people on the street they would

probably say things like “DSL,” “dial-up,” or even start naming their favorite websites or

browsing program. But web services aren't something that people use directly. A web

service is a service meant for consumption by another application or component, much in

the same way that session beans are meant to be used by other application components.

The Internet connects millions of computers across the world together to allow people to

communicate and access services provided by other people. Web services work in much

the same way, using the standard technologies already in place to allow applications to

communicate and provide services to other applications.

       Business logic can be put into session beans for enterprise applications and

accessed remotely as we learned earlier. But there may be some situations in which it is

undesirable or even impossible to allow this level of access to an enterprise application's

session beans. What if you don't control the network that the other components are on?

What if you don't have control over any aspect of the code that needs your business logic

(including the language it is written in)?

       Let's say that you have a business idea to create an authentication service.

Customers will be able to pass a username and password to your application from their

client applications and get a boolean value of true if the authentication succeeds, or false

if it does not. This would free developers from having to write authentication logic into

their applications, managing security policies, and maintaining a database of user

information. This would be easy to implement using session beans. But some customers

may be behind a firewall and unable to make a direct connection to the application server
hosting the session bean. Other customers might not be using Java in the client


       If you were able to use a ubiquitous protocol, one that is likely to be available

even in restricted networks, you could use that protocol to communicate with the client

application. Web services were designed for situations just like this. Rather than limiting

potential clients to only those using Java, web services allow applications to

communicate over the widely used HTTP protocol, the same protocol that powers the

World Wide Web. Most networks are Internet-accessible and it is increasingly unlikely

that HTTP traffic will be blocked. In addition, the technologies involved are accessible

from a wide variety of programming languages. This is just what Web Services do –

allow communication between two applications using standard technologies like HTTP

and XML.

       Web services use existing Internet application protocols like HTTP as a carrier for

messages between the web service and the client. The HTTP protocol becomes a sort of

box for shipping web services messages back and forth between applications. The basic

transport protocol that provides Internet connectivity is TCP/IP, without which there

would be no Web for the web services to be part of. Dependent upon that protocol is the

application protocol that wraps up the web service message. Normally, this would be the

end of the line – it is the protocol that web browsers and web servers use to communicate.

HTTP wasn't designed to carry information about remote method calls, however, so

another layer is needed to allow such information to be communicated. In the case of web

services this other layer is called SOAP (originally an acronym for Simple Object Access

Protocol), a protocol that defines the messages that are sent between applications so that
they can communicate useful messages to each other, like “run this method,” or “here is

the result of your message request.” The following diagram shows how the different

levels of protocols work together.

Figure 8.1: Web Service Messages

8.2 WSDL

       Java's web service API is called JAX-WS, for Java API for XML Web Services.

It uses the SOAP protocol (which in turn uses XML) to exchange messages between

applications. The services are defined by a WSDL (Web Services Description Language)

document. The WSDL document is yet another XML document that defines the

capabilities of the web service and allows remote applications to see which methods the

web service provides. One of the advantages of using NetBeans to develop web services

in Java is that the creation is greatly simplified. While it is a worthwhile activity to learn

XML, you will not have to write a single line of XML by hand to get a web service up

and running. Here is a sample of a simple web service with one method:

       <?xml version="1.0" encoding="UTF-8" standalone="yes"?>

       <!-- Generated by JAX-WS RI at http://jax- RI's version is JAX-WS RI

       hudson-417-SNAPSHOT. -->

       <definitions targetNamespace="http://ws.app1/"









  <xsd:import namespace="http://ws.app1/"




<message name="add">

 <part name="parameters" element="tns:add"/>


<message name="addResponse">

 <part name="parameters" element="tns:addResponse"/>


<portType name="NewWebService">

 <operation name="add">
  <input message="tns:add"/>

  <output message="tns:addResponse"/>



<binding name="NewWebServicePortBinding"





 <operation name="add">

  <soap:operation soapAction=""/>


   <soap:body use="literal"/>



   <soap:body use="literal"/>




<service name="NewWebServiceService">

 <port name="NewWebServicePort"


  <soap:address location="REPLACE_WITH_ACTUAL_URL"/>



       The types are defined in the following file, imported in the

<xsd:import> element. It defines the messages “add” (the message from the

client to the server) and “addResponse” (the return message from the server to the

client) and the parameters each message contains. The “add” message takes two

parameters of type “int” named “addend1” and “addend2.” The “addResponse”

message returns a single parameter of type “int” named “return,” which is the sum

of the two parameters received in the “add” message:

<xs:schema version="1.0" targetNamespace="http://svc/">

<xs:element name="add" type="tns:add"/>

<xs:element name="addResponse" type="tns:addResponse"/>

<xs:complexType name="add">


<xs:element name="addend1" type="xs:int"/>

<xs:element name="addend2" type="xs:int"/>



<xs:complexType name="addResponse">


<xs:element name="return" type="xs:int"/>



       The WSDL document contains several important elements:


<types>    -- The types element defines the acceptable types of data used in various

parts of the web service messages that correspond to data types in regular Java programs,

which define the type and range of values that can be stored in a variable. Types are

defined with XML schema.

<message>      -- The message element describes some communication between a web

service and a client. Messages are used in web service operations and are analogous to

parameters or return values in normal programs. A message could define some

information that is sent to the web service by the client (like a parameter passed to a

method) or information sent to the client from the web service (like the return value from

a method). Messages are composed of parts, which are associated with the types defined

in the WSDL document. For example, the message tag in the preceding example with the

name=”addResponse” attribute defines a message that contains a part named

“parameters.” The data that the “parameters” part can contain is defined by the XML

schema in the <types> element.

<bindings>      -- The bindings element describes the format of the message (like

SOAP) and protocols that the web service will use. Web services are not restricted to the

HTTP protocol. While HTTP is a very widespread protocol, it is not uncommon to bind a

web service to SMTP (the protocol underlying e-mail) for some applications.
<operation>       -- The operation element describes what the web service can do. It is

like a method or function in a traditional programming language. An operation is

described in terms of the messages that it sends and receives just as a Java method could

be described in terms of the parameters it takes and the value it returns. The “add”

operation in our example shows a request/response message pattern (a request is received

by the web service and a response is sent). Operations are not limited to the

request/response model. It is possible to send a request to a web service without getting a

response back or even for a web service to send output without having received a request.

Such messaging models often use the SMTP protocol, which does not rely on the

request/response pattern that HTTP does.

<portType>      -- The portType element describes the web service as a whole by

describing the operations that are available. While it is not the top-level element in our

example, it does the important work of tying together the operations and messages that

define the web service's functionality.

Table 8.1: Web service parts and their corresponding Java parts

  <portType>                                    Class
  <operation>                                   Method
  <message>                                     Method parameter or return value
  <types>                                       Data types (e.g., int, double, String, etc.)

       Having NetBeans generate this file automatically from the code is a great benefit.

It allows the programmer to concentrate on programming the logic for the web service
instead of spending the majority of the time writing XML documents.

       The most common transport for web service messages is the HTTP protocol. It is

a well-defined protocol that has been around for years and isn't likely to change much in

the near future. It is so ubiquitous that even PDAs and cell phones are using it now. In

addition to its widespread adoption, it has another property that makes it useful for web

services. HTTP is a response-request protocol. That is, when you send a request, you

expect a response. When you type an address in your web browser and nothing comes

back, you naturally assume something is wrong. This is somewhat analogous to the way

we expect methods in programs to behave. Even if we don't know what the method's

internal code looks like, we expect that if we call the method, it will return. In a sense we

are making a request to the method and expecting a response (a return value).

8.3 SOAP

       When some client application wants to use a web service it must create a port, or

stub, for the methods that are implemented in the web service. When methods are called

on the port, the application wraps up the method call in a SOAP request and sends it off

to the server. SOAP is a protocol or standard for wrapping up these types of requests in

XML to help facilitate communication. The server receives the request, executes the

method with the parameters sent by the client, and then sends the return value in a SOAP

response back to the client. Here is a sample SOAP request / response generated by the

method call: port.add(3, 2):

       SOAP Request:
 <?xml version="1.0" encoding="UTF-8"?>





     <ns2:add xmlns:ns2="http://ws.app1/">






SOAP Response:

 <?xml version="1.0" encoding="UTF-8"?>




     <ns2:addResponse xmlns:ns2="http://ws.app1/">




       As you can see from the sample, the request contains the method name (add) as an

element in the <S:Body> tag. The parameters are passed as elements contained within

the <ns2:add> element. The elements within the body element are defined by the web

service's WSDL (since not every web service will use elements named “addend1” or

“addend2”). The response contains the return value wrapped in the “return” tags. Once

the response has been received by the client the return value is parsed and returned to the

calling code as if it were a local method. We could write a program to generate and parse

these SOAP requests and responses, but luckily we don't have to. Using NetBeans to

create a web service in Java saves a great deal of time because neither the web service

nor the client code has to parse the XML in the messages. That will all be handled by the


8.4 Your First Web Service

       To get started with web services, we will create a simple “Hello World” web

service that prints out a friendly message.

1.              Open the NetBeans IDE.

2. Create a new project by choosing New → Project from the File menu to open the New

Project Wizard dialog. In the dialog, choose Web from the category list on the left and

choose Web Application from the Project list on the right. Click the Next button to

3. Enter a name for the web project and click Next to continue.
4. Accept the defaults on the next dialog box and click Finish to create the project.

5. Right-click on the project node and choose New → Web Service from the context

6. Name your web service HelloService and assign a package name. Click Finish to

create the web service.
7. A new node named Web Services appears under the web project and appears in the Editor pane. The Editor pane has a design view (the

default view) and a source view. Click the source button at the top of the Editor pane to

view the code.

8. Click the Design button at the top of the Editor pane to switch back to the Design

9. Click the Add Operation button in the upper left portion of the Design view.

10.In the Add Operation wizard, change the name to sayHello and click OK to create the

11. Click on the Source button at the top of the Editor pane to switch to the source code.

12. Edit the sayHello method and replace the default return statement to return the

String “Hello! Welcome to the wonderful world of Web


13. Click the Run button to start GlassFish. Additionally, you may need to choose Clean

and Build Main Project from the Build menu or use the keyboard shortcut SHIFT + F11

to deploy the project to the web container.

14. Expand the Web Services node in the project and right-click the HelloService web

service. Choose Test Web Service from the context menu to test the web service you just

15. Your web browser should automatically open to the web service tester. If it does not,

open your favorite web browser and point it to


16. Click the sayHello button to view the results of your web service.

8.5 Accessing Web Services

       Now that we know what a web service is, what it is used for, and how it behaves,

let's see what one actually looks like:

       package com.datavikings.converter;

       import javax.jws.WebMethod;

       import javax.jws.WebService;

       public class Converter {

               @WebMethod(operationName = "poundsToKilos")

               public double poundsToKilos(@WebParam(name =

       "pounds") double pounds) {

                      return pounds / 2.2;


               @WebMethod(operationName = "kilosToPounds")

               public double kilosToPounds(@WebParam(name =

       "kilos") double kilos) {

                      return kilos * 2.2;



       As you can see from the sample code, the @WebService annotation is used to

signal to the container that this is a web service. The publicly accessible methods are

decorated with the @WebMethod annotation. The @WebMethod annotation may take a

parameter called operationName, which maps the method to a web service operation

defined in the WSDL document. The parameters may additionally be dressed up with the

@WebParam annotation that takes a name parameter, which would create a customized

mapping of the parameter to a WSDL message part. The method signatures are

automatically generated by NetBeans when creating a web service and will take care of

putting the appropriate annotations in place as well.

       NetBeans makes accessing a web service just as easy as creating one. Here is a

simple example of a web service client:

       package com.datavikings.converterclient;
       public class WebServiceClient {

               public static void main(String[] args) {

                      try {

       com.datavikings.converter.ConverterService service =




port = service.getConverterPort();

                              double pounds = 180;

                              double result =


                              System.out.println(pounds + " pounds = "

+ result + "                                                kilos");


                      catch (Exception e) {





       The service is instantiated by creating a new object of the type defined by the web

service. Remember earlier when we drew an analogy between a web service and a class?

Now the analogy isn't just an analogy. The web service “object” reference can be used to

create a port. The port is what will be used locally to call the web service operations. You
can think of the port as a kind of remote control. When you push a button on your

television remote the operation happens remotely as if you had pushed the same button

on the television itself. The port is the remote control for the web service.

8.6 Web Services, Session Beans, and State

       Web services can be created as part of a web application or an enterprise

application. In fact, if you have business logic in a session bean already, you can turn it

into a web service with very little work. When creating a new web service in NetBeans,

the New Web Service wizard will ask if you want to create a new web service from

scratch or from an existing session bean. If you point the wizard to an existing session

bean it can automatically create the web service. The reason the conversion is so simple

is that, aside from the annotations and some XML, session beans and web services are

essentially just regular vanilla Java objects. A session bean can hide its implementation

details behind a Java interface and the web service hides its implementation details

behind the WSDL file. Once those details are worked out (generating the interface for

session beans or the WSDL for web services) the same class can be used for both.

       So we can see that web services and session beans can fill the same role, that of

providing business logic, but they do so in different ways. The session beans do so as part

of the overall Java Enterprise platform and web services as a language-agnostic service

that can be integrated into a stand-alone application. Although stateful session beans may

keep track of a client's state between invocations, HTTP and SMTP are at their core

stateless protocols.

       When the HTTP protocol was designed it was intended to be a stateless protocol,
that is to say that each request was seen by the protocol as a new conversation. There was

no mechanism for associating one request with another. As the Internet grew and

changed, methods were developed to allow the client and server to associate related

requests. This functionality is essential to e-commerce because without it, there would be

no way for websites to remember the contents of a virtual shopping cart between

requests. This is most often done by means of cookies, small key/value pairs that are

passed along in the HTTP request. A session ID is normally sent with each request so that

a server that supports sessions can look up information that is relevant to the current

request or prior requests.

       Imagine waiting for a table at a crowded restaurant. The hostess tells you that

there is an hour wait, so you give your name and wait for an hour. When you go back to

ask how much longer you must wait, you give your name again so the hostess can check

the list and see your position on the waiting list. If you didn't give your name, she might

think you weren't on the list and make you wait another hour (after all, it's busy and she

can't remember every face that comes in).

       Obviously, the stateful session bean has the advantage when it comes to

maintaining state information about a client. Although there are some advanced methods

for maintaining state in web services, they are limited to the HTTP protocol. This means

that any web services that maintain state cannot be bound to other protocols such as

SMTP. The particular techniques for implementing such stateful web services are beyond

the scope of this text.

8.7 RESTful Web Services
        REST stands for Representation State Transfer. It is a term coined by Roy

Fielding in his doctoral dissertation. Essentially REST is an architectural style for

distributed systems. The classic example of a REST system is the World Wide Web. The

client begins by viewing a page, which is a representation of some information. The

representation that the client receives places the client in a particular state. The client is

given a set of URLs in the document that make other resources (or representations of

other resources) available. Each URL presented to the client represents a resource, which

could in turn provide more URLs to allow the client to drill down deeper into the

resource or move to resources that are related to the current resource. By following these

links, the client's state changes and the representations that are referenced by the

hyperlinks are transferred to the client.

       Web services may also be built around this concept. Instead of using SOAP as a

message format, the RESTful way of doing things uses the HTTP protocol directly to

transmit information. Messages that are intended to receive information from the web

service use the GET command from the HTTP protocol. Similarly, messages that are

intended to provide the web service with some information from the client to update a

resource would use a PUT command, and instructions to delete something would be

issues from the client as DELETE commands. The PUT and DELETE commands are not

often used, but are part of the HTTP protocol specification. Data sent to the web service

is placed in the body of a PUT request, but does not have to conform to the SOAP

standard. It is up to the web service and the client to understand the format of the

messages, whether they are XML or another technology such as JSON.

       The four basic HTTP methods map neatly onto the four basic operations for a
database system:

   ·   GET – Read

   ·   POST – Create

   ·   PUT – Update

   ·   DELETE – Delete

       It is often convenient to think of this mapping, but it also highlights an important

and often overlooked rule of web development. GET requests should be idempotent. We

discussed this in chapter one, but it bears repeating here. The GET request retrieves a

representation of a resource. It should never alter the resource it is requesting. To update

a resource, use the PUT method. To create a new resource, use the POST method. A GET

request should be safe for the resource, leaving it in the same state it was before the

request and able to be sent multiple times with no side effects.

       A resource in a RESTful system could be anything. In the classic example of the

World Wide Web, HTML documents are resources, as are the images that may be

referenced in the documents. A resource should be identifiable by a unique URL. If you

have ever used a web application that does not identify each screen with a unique URL,

you will immediately see the advantage of addressing resources this way. Imagine you

are filing your taxes. You spend the better part of 45 minutes entering numbers into web

forms and clicking the Next button on each page only to realize that you left your last tax

form on your desk at work. But you can't simply bookmark the application, because each

page was submitted to the same generic URL via POST. If you try to go back to the page

after bookmarking it, you will have to start all over. Rather than require a sequence of

specific inputs in a particular order to retrieve a resource, each resource in a RESTful
system has its own URL.

       Imagine that you are designing a web service for a travel agency to allow agents

to create, view, and update travel itineraries via a web service. Each resource involved in

the travel plan (such as airline flights) is exposed under a specific URL. Retrieving

http://server/WebService/resources/flights/ via HTTP would return a list of all available

flights. Each of the flights in the list is in turn represented by a URL that is an extension

or refinement of the /resources/flights/ path. To choose flight 815, for example, the URL

corresponding to that resource might be http://server/WebService/resources/flights/815/.

If further refinement is available the web service may allow a client to drill down to seat

resources under flight 815 to see the available seats on the flight. If other resources are

involved with the flight resource (such as destinations), the URLs that correspond to

those resources would also be present, allowing the client to jump to the related resource.

       As you can see from the listing below, the RESTful web service request is much

simpler than its SOAP counterpart. There is no bulky XML to parse – the entire

semantics of the resource being accessed are in the URL.

       Sample RESTful Web Service request:

       Request: GET



       Sample RESTful Web Service response:

       <?xml version="1.0" encoding="UTF-8"?>


       <airlinename>United Airlines</airlinename>

       <arrairport>New York Newark Intl Arpt




       <depairport>Oakland (OAK)</depairport>




       <flightnum>United Airlines 71</flightnum>







       The RESTful web service reply does contain XML in our example. The advantage

of XML here is that the data describes itself very simply. In the above example a flight

resources was requested, specifically, flight 1. The flight element in the response contains

several pieces of information such as the airline, airport, and time of departure. It also

contains a reference to a trip, which is represented by another URL. The client that

requested the flight resource now has, by virtue of the tripRef element, a URL to
follow to get information about the related trip. Not all resources can be represented by

XML, however. Recall that in the World Wide Web, images are resources as well, with

their own representation. Today many different types of resources are represented on the

Internet. Images, videos, music, documents, and even executable programs are all

represented as resources out in the wilds of the Web, each with their own specific

representation. The important thing is that the client can understand the representation.

After all, what good is access to a resource if you can't understand it? For this reason

XML is a popular choice for representing resources that do not already have a

standardized representation format.

       Because a REST system is session-less, RESTful web services do not maintain

state between calls. Each URL should uniquely identify a resource and should contain all

information necessary to locate a specific resource, making the need for session tracking

unnecessary. The URLs do not actually need to exist as part of a server's file system (as

you would expect from a web server serving up static pages), but they must be unique so

that the web service can use the URL to identify the resource that is being requested. In

general, web services built around REST are not described in terms of what they can do

as much as what they can offer. That is, the emphasis is not as much on implementing

business logic as it is exposing resources to the client.

       This is one of the reasons that state is not emphasized in REST systems – the

resources that are being represented are not business methods that need to keep track of

the client's state. Instead, they are things that have their own state that the client can view

or update. To make an analogy with the English language, RESTful web services are

nouns (things that can be represented and shared), whereas JAX-WS web services are
verbs (actions that are performed). Put another way, JAX-WS web services expose

methods that can be executed, whereas RESTful web services expose data elements that

can be accessed. In this way RESTful web services complement JAX-WS web services

just as session beans complement entity classes in Java Enterprise applications. For a

stateful JAX-WS web service method like a hit counter for a website, it is important to

uniquely identify the client and also to save information about the previous calls that the

client made (otherwise, the hit counter would be inaccurate, either displaying the total

number of hits from all clients or displaying just 1 hit because it cannot remember the

ones that came before). For a RESTful web service that represents a database, the state of

the client is mostly irrelevant. The database itself keeps track of its own state and the web

service offers a representation to whoever asks for it, regardless of whether or not they

have previously seen the information. The state of the resource is what is important rather

than the client.

       As a matter of fact, the session/entity class analogy is more than a simple

metaphor. Just as JAX-WS web services can be easily created from existing session

beans, RESTful web services can be created from entity classes in a similar fashion,

exposing the underlying database as a resource. Lab 3 will show how to create a RESTful

web service from a simple database.

8.8 Practice Labs

8.8.1 Lab 1: Current Time Web Service
1.               Open NetBeans by double-clicking the NetBeans icon.

2. Go to File → New Project to start the New Project wizard.

3. In the New Project wizard, choose Web in the category list on the left and Web

Application from the project list on the right and click Next.
4. At the next prompt, enter WSLab as the project name.
5. At the next prompt, accept the defaults for the project, making sure that GlassFish is

set as the server and click Finish.
6. When the newly created project opens, right-click on the top-level node WSLab and

choose New → Web Service from the context menu to start the New Web Service

7. In the New Web Service wizard menu, enter Time as the web service name, provide a

package name for the web service, and make sure that the Create Web Service from

Scratch option is selected.
8. Expand the WSLab node and the Web Services subnode will reveal the newly created

web service named Time. Double-click the web service to open it in the Editor window in

Design mode, which displays a summary of the operations and some Quality of Service

9. Click Source at the top of the Editor pane to view the source code for the web service.

10. Right-click on the Time web service and choose Add Operation from the context

menu to start the Add Operation wizard.

11. In the Add Operation wizard, set the name to getTime and keep the return type as

java.lang.String (the default). Click OK to add the operation to the web service.
12. The source code for the newly created operation appears in the class file for the web


13. In the file, locate the getTime() method and replace the automatically

generated return statement with the following code:

return new Date().toString();

The function should now look like this:
14. A red underline will appear under the word Date() in the code listing. Click on the

lightbulb icon at the right edge of the Editor window (it will appear to the right of the line

of code in question) and choose Add Import for java.util.Date from the context menu to

import the Date class from the java.util package.

15. Click the run icon in the toolbar to run the web application. This will automatically

start GlassFish and deploy the application. It will also open a web browser to the

application's default Hello World page, which you may close.

16. Right-click the Time web service in the Project pane and choose Test from the

context menu. This will open a web browser that will display a Servlet designed to allow

you to test the web service.
17. On the web service tester page, click the getTime button to make the Servlet invoke

the getTime() method in the web service. The next page will display the return value

and the SOAP request and response.

8.8.2 Lab 2: Current Time Web Service Client

1.             Open NetBeans by double-clicking the NetBeans icon.

2. Go to File → New Project to start the New Project wizard.
3. In the New Project wizard, choose Java in the category list on the left and Java

Application from the project list on the right and click Next.

4. At the next prompt, enter WSClient as the name of the application and click Finish.
5. When the newly created project opens, right-click on the top-level node WSClient and

choose New → Web Service Client from the context menu to start the New Web Service

Client wizard.
6. The New Web Service Client wizard asks where the web service is located. You can

specify a project, a local file, or a URL that points to a WSDL file.
7. Choose the Project option and click the Browse button to browse. In the browse

window, expand the WSLab project (from Lab 1) and choose the Time web service.

Click OK.

8. The box next to the project option in the New Web Service Client dialog is now

populated with the URL of the WSDL file that describes the Time service in the WSLab
project. Click Finish to add the web service client.

9. Open in the editor pane (it should have opened automatically when the

project was created). Right-click inside the main() method and choose Insert Code

→ Call Web Service Operation from the context menu.
10. In the Select Operation to Invoke dialog box, expand the nodes until you see the

getTime operation and click OK.
11. The code to access the getTime operation will be automatically inserted at the cursor

position in the file. The resulting Main class should look like this:

public class Main {


      * @param args the command line arguments


     public static void main(String[] args) {

           // TODO code application logic here
          String time = getTime();

          try {

         // Call Web Service Operation

         com.datavikings.webservice.TimeService service = new


          com.datavikings.webservice.Time port =


           // TODO process result here

                           java.lang.String result = port.getTime();

                           System.out.println("Result = "+result);

                       } catch (Exception ex) {

                           // TODO handle custom exceptions here




Click the run icon in the toolbar to run the application.

12. The client's output will show up in the Output pane of the NetBeans IDE at the

bottom of the window.
8.8.3 Lab 3: RESTful Web Service

1.               Open NetBeans by double-clicking the NetBeans icon.

2. Go to File → New Project to start the New Project wizard.

3. In the New Project wizard, choose Web in the category list on the left and Web

Application from the project list on the right and click Next.
4. At the next prompt, enter RESTLab as the project name.
5. At the next prompt, accept the defaults for the project, making sure that GlassFish is

set as the server and click Finish.

6. When the newly created project opens, right-click on the top-level node RESTLab and

choose New → Other from the context menu to start the New File wizard.
7. In the New File wizard, choose Persistence from the category list on the left and

choose Entity Classes from Database from the file type list on the right and click Next.
8. At the next dialog, choose New Data Source from the drop-down menu.
9. In the Create Data Source dialog box, enter jdbc/travel as the JNDI name and choose

the TRAVEL database from the Database Connection drop-down list and click OK.

10. The list of Available Tables on the left will show several tables. Highlight the Flight

table and click the Add > button to move it and all of the tables it references to the

Selected Tables list on the right. Click Next.
11. On the next screen, click the Create Persistence Unit button to create a persistence

unit for this project. Accept the default values and click OK.
12. Enter lab.restful in the package name field and click Finish to create the entity


13. Right-click on the top-level node in the project again and choose New → Other from

the menu to open the New File wizard.
14. Select Web Services from the category list on the left and choose RESTful Web

Service from Entity Classes on the right. Click Next.
15. Click the Add All >> button to move all of the available entity classes from the

Available Entity Classes list to the Selected Entity Classes list and click Next.

16. Click Finish on the next dialog to accept the default package names and create the
web service.

17. Test the newly-created RESTful web service by right-clicking on the top-level node

in the project and selecting Test RESTful Web Services from the context menu.
18. NetBeans will start GlassFish and open your default browser to a page that will allow

you to test the web service. On the right side of the page you will see the table resources

in the Travel database. Click on flights in the list and a menu will appear on the right.

Choose GET (application/xml) from the drop-down menu and click the Test button to

view the first 10 records of the flights table in the database.
8.9 Summary

       In this chapter we discussed web services, a powerful, platform-independent tool

for enabling communication between applications. Web services use existing standard

technologies to make method calls over a commonly used application protocol such as

HTTP or SMTP. The web service itself is described in a WSDL file, which is an XML

document that contains definitions for the bindings, messages, and types used in the web

service communication. Web services play much the same role as session beans,

providing business logic to an application. When used with the HTTP protocol a web

service can maintain state between calls by leveraging sessions in the HTTP protocol.

When HTTP sessions are used, both the client and the web service must take steps to

enable use of the session management feature.

       Web services based on the REST architectural style do not save state between

requests and do not use SOAP as a message format. RESTful web services expose

representations of resources that clients may request. A RESTful web service may expose

a resource for Create, Read, Update, and Delete (CRUD) operations.
8.10 Chapter Review

1. What is a web service?

       a. An application that people use to access the Internet.

       b. A service that applications may access through common standard protocols.

       c. A method for applications to access the network.

       d. A service that companies use to provide access to the Internet.

2. What is one advantage of using standard protocols to access web services?

       a. Commonly used protocols like HTTP are not likely to be blocked by firewalls.

       b. HTTP and SMTP protocols were designed as tunneling protocols.

       c. Commonly used protocols like WSDL are easy to implement.

       d. The SOAP protocol guarantees delivery of application messages.

3. Name two common application protocols used for communication with web services.

       a. WSDL

       b. SMTP

       c. HTTP

       d. HTML

4. What is the purpose of a WSDL document?

       a. To enable XML support in a web application.

       b. To tunnel the data sent to a web service.

       c. To encapsulate the data sent to a web service.

       d. To describe a web service's capabilities.

5. Which of the following are not main tags used in a WSDL document (choose two)?

       a. types
       b. message

       c. operations

       d. return

6. How are session beans and JAX-WS web services similar?

       a. Both require a Java client.

       b. Both encapsulate business logic.

       c. They use the same communication protocols.

       d. There are no similarities between the two.

7. How are session beans and JAX-WS web services different?

       a. Web services cannot be created from a POJO (Plain Old Java object).

       b. Web services use standard Internet protocols such as HTTP or SMTP for


       c. Web services cannot be accessed remotely.

       d. Web services do not encapsulate business logic.

8. When is it advantageous to use web services instead of session beans?

       a. When the client platform or development environment is unknown or may vary.

       b. When the client does not have Internet access.

       c. When the client and business logic reside on the same JVM instance.

       d. After normal business hours.

9. What does REST stand for?

       a. Representation of Electronic State Transmission

       b. Resource State Transfer

       c. Representation State Transfer
          d. Rotten Eggs Smell Terrible

10. Name a commonly used REST system.

          a. E-mail

          b. The World Wide Web

          c. Databases

          d. Session Beans

11. True or False: RESTful web services maintain state between requests from the same


12. What is the name of the message protocol that JAX-WS web services use?

          a. SOAP

          b. WSDL

          c. HTML

          d. REST

13. RESTful web services do not use SOAP. How does a RESTful web service know the

difference between a request to view a resource and a request to update a resource?

          a. The HTTP status code returned from the web service.

          b. A command embedded in the HTTP POST body.

          c. The HTTP command used to access the resource.

          d. Different URLs correspond to different actions.

14. Which type of web service lends itself well to sharing resources such as databases?

          a. RESTful

          b. JAX-WS

          c. SOAP
       d. XML

15. Which type of web service lends itself well to implementing business logic?

       a. RESTful

       b. JAX-WS

       c. SOAP

       d. XML

Answers to Chapter Review Questions



3.B & C












8.11 Exercises

1.Web services can also be added to the web module of an enterprise application.

Implement exercise 2 from Chapter 6: Session Beans as a web service.

2. Write a hit counter web service that stores the number of times the getCount()

method has been executed. Write Two Servlets, ServletA and ServletB, that both display

getCount(). Test the web service using the Servlets. Are the counts accurate? Why or

why not?

3.* Modify the web service in exercise 2 so that the hit counter will be accurate for each

client. There is more than one way to accomplish this (hint: use entities to persist the

number of hits for a client to a database).

* denotes a challenging exercise

To top