You are on page 1of 32

UNIT-V

AJAX: Ajax Client Server Architecture-XML Http Request Object-Call Back Methods; Web
Services: Introduction- Java web services Basics – Creating, Publishing, Testing and Describing a
Web services (WSDL)-Consuming a web service, Database Driven web service from an web
application – SOAP.

Introduction to AJAX:
AJAX is an acronym for Asynchronous JavaScript And XML. AJAX is a new technique for
creating better, faster and interactive web applications with the help of JavaScript, DOM, XML, HTML,
CSS etc. AJAX allows you to send and receive data asynchronously without reloading the entire web page.
So, it is fast. AJAX allows you to send only important information to the server not the entire page. So
only valuable data from the client side is routed to the server side. It makes your application interactive and
faster. Ajax is the most viable Rich Internet Application (RIA) technique so far.

AJAX is a technique for creating fast and dynamic web pages. AJAX allows web pages to
be updated asynchronously by exchanging small amounts of data with the server behind the
scenes. This means that it is possible to update parts of a web page, without reloading the whole
page.

Where it is used?
There are too many web applications running on the web that are using AJAX Technology. Some
are:
1. Gmail
2. Face book
3. Twitter
4. Google maps
5. YouTube etc.,

AJAX stands for Asynchronous Java Script and XML. It allows the various client requests
at the server, the server should process the required processing, and automatically loads the page
without refreshing the page i.e., without user need to move from one page to other page.
Asynchronous means that the script will send a request to the server, and continue it's
execution without waiting for the reply. As soon as reply is received a browser event is fired,
which in turn allows the script to execute associated actions.
Synchronous Vs. Asynchronous Application Before understanding AJAX, let’s understand classic
web application model and AJAX Web application model.
Synchronous (Classic Web-Application Model) A synchronous request blocks the client until

Dr. P. CHITRALINGAPPA Page 1 of 32


operation completes i.e. browser is not unresponsive. In such case, JavaScript Engine of the browser is
blocked. As you can see in the above image, full page is refreshed at request time and user is blocked.

As you can see in the above image, full page is refreshed at request time and user is
blocked until request completes.

Asynchronous (AJAX Web-Application Model) An asynchronous request doesn’t block the


client i.e. browser is responsive. At that time, user can perform other operations also. In such case,
JavaScript Engine of the browser is not blocked. As you can see in the above image, full page is not
refreshed at request time and user gets response from the AJAX Engine. Let's try to understand
asynchronous communication by the image given below.

AJAX Components AJAX is not a technology but group of inter-related technologies.


AJAX Technologies includes:
 HTML/XHTML and CSS
 DOM
 XML
 JSON (JavaScript Object Notation)
 JavaScript
 XMLHttpRequest Object
 HTML/XHTML and CSS-These technologies are used for displaying content and style. It is
mainly used for presentation.

Dr. P. CHITRALINGAPPA Page 2 of 32


 DOM-It is used for dynamic display and interaction with data.
 XML or JSON (JavaScript Object Notation)-For carrying data to and from server. JSON is like
XML but short and faster than XML.
 XMLHttpRequest Object For asynchronous communication between client and server.
 JavaScript It is used to bring above technologies together. Independently, it is used mainly for
client-side validation.
Advantages of AJAX
 Reduce the traffic travels between the client and the server.
 Response time is faster so increases performance and speed.
 You can use JSON (JavaScript Object Notation) which is alternative to XML. JSON is
key value pair and works like an array.
 You can use Firefox browser with an add-on called as Firebug to debug all Ajax calls.
 Ready Open-source JavaScript libraries available for use – JQuery.
 AJAX communicates over HTTP Protocol.
Disadvantages of AJAX
 It can increase design and development time
 More complex than building classic web application
 Security is less in AJAX application as all files are downloaded at client side.
 Search Engine like Google cannot index AJAX pages.
 JavaScript disabled browsers cannot use the application.
 Due to security constraints, you can only use it to access information from the host that
served the initial page. If you need to display information from another server, it is not
possible within the AJAX.

How AJAX Works?


AJAX communicates with the server using XMLHttpRequest object. Let's understand the
flow of AJAX with the following figure:

1. User sends a request from the UI and a JavaScript call goes to XMLHttpRequest object.
2. HTTP Request is sent to the server by XMLHttpRequest object.
3. Server interacts with the database using JSP, PHP, Servlet, ASP.net etc.
4. Data is retrieved.
5. Server sends XML data or JSON data to the XMLHttpRequest callback function.
6. HTML and CSS data is displayed on the browser.

Dr. P. CHITRALINGAPPA Page 3 of 32


Ajax Client-Server Architecture:
Ajax applications add a layer between the client and the server to manage communication
between the two.
 When the user interacts with the page, the client creates an XMLHttpRequest object
t o manage a request (Step 1).
 The XMLHttpRequest object sends the request to the server (Step 2) and awaits the
response.
 The requests are asynchronous, so the user can continue interacting with the application on
the client side while the server processes the earlier request concurrently.

Dr. P. CHITRALINGAPPA Page 4 of 32


 Other user interactions could result in additional requests to the server (Steps 3 and 4).
 Once the server responds to the original request (Step 5), the XMLHttpRequest object that
issued the request calls a client-side function to process the data returned by the server.
 This function—known as a callback function—uses partial page updates (Step 6) to
display the data in the existing web page without reloading the entire page.
 At the same time, the server may be responding to the second request (Step 7) and the
client side may be starting to do another partial page update (Step 8).
The callback function updates only a designated part of the page. Such partial page
updates help make web applications more responsive, making them feel more like desktop
applications. The webapplication does not load a new page while the user interacts with it.
XMLHttpRequest object
Ajax applications use the XMLHttpRequest object to initiate and manage the submission
of data requests to web servers and to monitor and handle the receipt of server data. The
XMLHttpRequest object can be used to exchange data with a server behind the scenes. This means
that it is possible to update partsof a web page, without reloading the whole page.
The XMLHttpRequest object can be used to request data from a web server.
TheXMLHttpRequest object is a developers dream, because you can: Update a web page without
reloading the page. Request data from a server - after the page has loaded.

XMLHttpRequest object plays a important role:

XMLHttpRequest object plays a important role:


1. User sends a request from the UI and a javascript call goes to XMLHttpRequest object.

2. HTTP Request is sent to the server by XMLHttpRequest object.

3. Server interacts with the database using JSP, PHP, Servlet, ASP.net etc.

4. Data is retrieved.

5. Server sends XML data or JSON data to the XMLHttpRequest callback function.

6. HTML and CSS data is displayed on the browser.

Dr. P. CHITRALINGAPPA Page 5 of 32


XMLHttpRequest Methods
The XMLHttpRequest object provides access to two methods that facilitate connecting to
webservers and submitting requests. A brief explanation of these methods is provided next.
 open()-Establishes a connection to a web server.
 send()-Sends a request to a web server.
The open() method is used to initiate a connection to the web server. Once connected, you
will use various XMLHttpRequest properties, to send data requests and then to monitor them once
they are started (which is done using the send() method).

Method Description

new XMLHttpRequest() Creates a new XMLHttpRequest object

abort() Cancels the current request

getAllResponseHeaders() Returns header information

getResponseHeader() Returns specific header information

open(method,url,async,user,psw) Specifies the request

method: the request type GET or POST


url: the file location
async: true (asynchronous) or false (synchronous)
user: optional user name
psw: optional password

send() Sends the request to the server


Used for GET requests

send(string) Sends the request to the server.


Used for POST requests

setRequestHeader() Adds a label/value pair to the header to be sent

XMLHttpRequest Properties
In order to specify the type of data that your Ajax applications expect to receive from the
web server and to monitor and respond to that data once it has been received from the web server,
you need to work with different XMLHttpRequest properties.

Dr. P. CHITRALINGAPPA Page 6 of 32


Property Description

onreadystatechange Defines a function to be called when the readyState property


changes

readyState Holds the status of the XMLHttpRequest.


0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready

responseText Returns the response data as a string

responseXML Returns the response data as XML data

status Returns the status-number of a request


200: "OK"
403: "Forbidden"
404: "Not Found"

statusText Returns the status-text (e.g. "OK" or "Not Found")

WORKING WITH THE XMLHTTPREQUEST OBJECT


Using XMLHttpRequest objects to establish connections to web servers, specifying data
requests, and then handling the data that is returned is a multi-step process.
Instantiating the XMLHttpRequest Object
The first step in working with the XMLHttpRequest object is to instantiate it.

var xhttp = new XMLHttpRequest();

Opening a New Connection


The next step after instantiating the XMLHttpRequest object is to establish a connection
with the web server using the open() method. This method has the following syntax.

xhttp.open("GET", "ajax_info.txt", true);


xhttp.send();
Waiting for the Web Server’s Response
Once you have instantiated the XMLHttpRequest object and specified the file that you
want to access using its open() method. The XMLHttpRequest object cycles through a number of
different states as it goes through the process of sending an HTTP request and then waiting for
and finally receiving data back from the web server. Specifically, the XMLHttpRequest object

Dr. P. CHITRALINGAPPA Page 7 of 32


exposes two properties that let you know the overall status of an HTTP request. These properties
are the readyState and status properties.
The readyState property, determine when the application has finished receiving the data.
The readyState property can report any of the values.
The status attribute, you can determine whether an HTTP request was successful.
Specifically, you need to make sure that the value assigned to the status property is 200.
The XMLHttpRequest object also has a property named onreadystatechange that can be
used to manage your applications’ asynchronous operations.

Handling the Web Server Response


Specify the type of data that your application expects to receive. This is done by one of the
XMLHttpRequest object properties listed here:
• responseText. The data is returned as plain text.

• responseXML. The data is returned as XML.

The following statement demonstrates how to set up your Ajax application to handle text data
returned by the web server.

RequestObj.innerHTML = Request.responseText;
Alternatively, you can set up your application to process XML data, as demonstrated here:
RequestObj.innerHTML = Request.responseXML;
Example:
<!DOCTYPE html>
<html>
<body>
<div id="demo">
<h1>The XMLHttpRequest Object</h1>
<button type="button" onclick="loadDoc('ajax_info.txt', myFunction)"> Change
Content </button>
</div>
<script>
function loadDoc(url, cFunction) {
var xhttp;
xhttp=new XMLHttpRequest ();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
cFunction(this);
}
};
xhttp.open("GET", url, true);
xhttp.send();

Dr. P. CHITRALINGAPPA Page 8 of 32


}
function myFunction(xhttp) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
</script>
</body>
</html>
Callback Functions
The stateChange function is the callback function that’s called when the client receives the
response data. function stateChange as the event handler for the XMLHttpRequest object’s
readystatechange event.
Whenever the request makes progress, the XMLHttpRequest object calls the
readystatechange event handler. This progress is monitored by the readyState property, which has
a value from 0 to 4.
0-The request is not initialized
1-The request has been set up
2- The request has been sent
3- The request is in process
4- The request is complete

The value 0 indicates that the request is not initialized and the value 4 indicates that the
request is complete. If the request completes successfully use the XMLHttpRequest object’s
responseText property to obtain the response data and place it in the div element named
contentArea.
Example:
<!DOCTYPE html>
<html>
<body>
<div id="demo">
<h1>The XMLHttpRequest Object</h1>
<button type="button" onclick="loadDoc('ajax_info.txt', myFunction)"> Change
Content </button>
</div>
<script>
function loadDoc(url, cFunction) {
var xhttp;
xhttp=new XMLHttpRequest ();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
cFunction(this);
}

Dr. P. CHITRALINGAPPA Page 9 of 32


};
xhttp.open("GET", url, true);
xhttp.send();
}
function myFunction(xhttp) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
</script>
</body>
</html>

Introduction web services


A software component stored on one computer that can be accessed via method calls
by anapplication (or other software component) on another computer over a network
Web services is a standardized way or medium to propagate communication between
the client and server applications on the World Wide Web. I n t h i s c h a p t e r will
d i s c u s s various components of web services like SOAP, WSDL, REST, and how they
operate. A Web service is a software service used to communicate between two devices on a
network. More specifically, a Web service is a software application with a standardized way of
providing interoperability between disparate applications. It does so over HTTP using
technologies such as XML, SOAP, WSDL, and UDDI.
Legacy Technologies:
Technologies Languages
Socket Programming
RMI (Remote Method Invocation) Java
EJB (Enterprise Java Beans)
DCOM (Distributed Component) .Net
RPC C/C++
CORBA (Common Object Request Broker Architecture) Specification

Advantages:

1. Exposing Business Functionality on the network - A web service is a unit of managed


code that provides some sort of functionality to client applications or end users. This
functionality can be invoked over the HTTP protocol which means that it can also be
invoked over the internet. Nowadays all applications are on the internet which makes the
purpose of Web services more useful. That means the web service can be anywhere on the
internet and provide the necessary functionality as required.

Dr. P. CHITRALINGAPPA Page 10 of 32


2. Interoperability amongst applications - Web services allow various applications to talk
to each other and share data and services among themselves. All types of applications can
talk to each other. So instead of writing specific code which can only be understood by
specific applications, you can now write generic code that can be understood by all
applications
3. A Standardized Protocol which everybody understands - Web services use
standardized industry protocol for the communication. All the four layers (Service
Transport, XML Messaging, Service Description, and Service Discovery layers) uses well-
defined protocols in the web services protocol stack.
4. Reduction in cost of communication - Web services use SOAP over HTTP protocol, so
you can use your existing low-cost internet for implementing web services.
Web Services-Architecture, Components and Types:
A web service is 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 HTTP. Several Java
APIs facilitate web services. In this chapter, we’ll be dealing with APIs that are based on the
Simple Object Access Protocol (SOAP)—an XML-based protocol that allows web services and
clients to communicate, even if the client and the web service are written in different languages.
There are other web services technologies, such as Representational State Transfer (REST).
Web Services-Architecture
Web Services architecture comprises three entities i.e. a Client, a Web Server, and an
Internet to carry out the operation. The operation is nothing but the request and response in a
client-server architecture. A Client is typically a set of all the applications or software systems that
requests a Web Service thereby making it a Service Consumer. A Web Server is a set of all
applications or software systems that provide Web Service. Every Web Service requires a network
to perform and this results in the third entity called the Internet.

The working diagram of a Web Service is defined by the three components shown below.
 Service Requestor (Find())
 Service Provider (Publish())
 Service Registry or Repository (Bind())
The first phase is the Publish() phase where a Service Provider feeds all the details about a
Web Service in a Service Registry or Repository.
The second phase is Find() where a Service Request mainly the client application finds the
details about Web Service from a repository (also has WSDL XML file).

Dr. P. CHITRALINGAPPA Page 11 of 32


The last phase is Binding() where the client application or the Service Requester synchronizes
with the Service Provider for the final implementation of the Web Service.

Components of Web Service


1. SOAP
Web Services use the Simple Object Access Protocol (SOAP) which uses XML as a
payload or request body. This is a stateful protocol as there is no independent method for the
specific type of operation.
All the requests and responses are carried at once through XML and no independent methods like
GET, PUT, POST or DELETE are explicitly provided.
2. WSDL
SOAP request makes use of Web Services Description Language (WSDL) which is a
very useful component of Web Service. This defines where the Web Service actually resides and
also the type of Web Service to be picked up for a specific request. This makes use of an XML file
that describes the Web Service functionality.
3. UDDI
UDDI stands for Universal Description Discovery and Integration. There is a service
provider who provides the Web Service. Hence, for a particular service provider, this UDDI is
used for describing, discovering and publishing those Web Services. UDDI is responsible for
letting a client find out (UDDI provides a repository for WSDL) where the WSDL’s XML file is
located. This is how a Web Service is defined and described.
4. STUB
Stub libraries must be installed on both the client and server side. A client stub is
responsible for conversion of parameters used in a function call and deconversion of results passed
from the server after execution of the function. A server skeleton, the stub on the server side, is

Dr. P. CHITRALINGAPPA Page 12 of 32


responsible for deconversion of parameters passed by the client and conversion of the results after
the execution of the function.
5. SKELETON
 Skeleton is a predefined class located at Server machine.
 It will receive SOAP request from client machine and generate SOAP response
through HTTP protocol.
6. HTTP

Java webservices
A web service is 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 HTTP. Several Java
APIs facilitate web services. In this chapter, we’ll be dealing with APIs that are based on the
Simple Object Access Protocol (SOAP)—an XML-based protocol that allows web services and
clients to communicate, even if the client and the web service are written in different languages.
There are other web services technologies, such as Representational State Transfer (REST).

Java Webservices APIs


Sun Micro systems has provided four types APIs to develop Web services:
 JAX-RPC (Java API for XML-Remote Procedure Call)jdk1.4
 JAX-M (Java API for XML-Messaging) jdk1.4
 JAX-WS (Java API for XML-Web Service) jdk1.5
 JAX-RS (Java API for XML-Restful Service) jdk1.6

Dr. P. CHITRALINGAPPA Page 13 of 32


Types of Web Service

There are two types of web services:

o RESTful Web Services


o SOAP Web Services

RESTful Web Services

REST stands for REpresentational State Transfer. It is developed by Roy Thomas


Fielding who also developed HTTP. The main goal of RESTful web services is to make web
services more effective. RESTful web services try to define services using the different concepts
that are already present in HTTP. REST is an architectural approach, not a protocol. It does not
define the standard message exchange format. We can build REST services with both XML and
JSON. JSON is more popular format with REST.

RESTful Service Constraints

o There must be a service producer and service consumer.


o The service is stateless.
o The service result must be cacheable.
o The interface is uniform and exposing resources.
o The service should assume a layered architecture.

Advantages of RESTful web services

o RESTful web services are platform-independent.


o It can be written in any programming language and can be executed on any platform.
o It provides different data format like JSON, text, HTML, and XML.
o It is fast in comparison to SOAP because there is no strict specification like SOAP.
o These are reusable.
o These are language neutral.

SOAP Web Services

Dr. P. CHITRALINGAPPA Page 14 of 32


REST defines an architectural approach whereas SOAP poses a restriction on the format of
the XML. XML transfer data between the service provider and service consumer. Remember that
SOAP and REST are not comparable.

SOAP: SOAP acronym for Simple Object Access Protocol. It defines the standard XML
format. It also defines the way of building web services. We use Web Service Description
Language (WSDL) to define the format of request XML and the response XML.

Creating, Publishing, Testing and Describing a Web Service

A web service is 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 HTTP. Several Java
APIs facilitate web services. In this chapter, we’ll be dealing with APIs that are based on the
Simple Object Access Protocol (SOAP)—an XML-based protocol that allows web services and
clients to communicate, even if the client and the web service are written in different languages.
There are other web services technologies, such as Representational State Transfer (REST).

1. Creating a Web Application Project and Adding a Web Service Class in NetBeans
Creating a Web Application Project in Netbeans 5.5
To create a web application, perform the following steps:
1. Select File > New Project to open the New Project dialog.
2. Select Web from the dialog’s Categories list, then select Web Application from the Projects list.
Click Next >.
3. Specify the name of your project (HugeInteger) in the Project Name field and specify where
you’d like to store the project in the Project Location field. You can click the Browse button to
select the location.
4. Select Sun Java System Application Server from the Server drop-down list.
5. Select Java EE 5 from the J2EE Version drop-down list.
6. Click Finish to dismiss the New Project dialog
This creates a web application that will run in a web browser. When you create a Web Application
in Netbeans, the IDE generates additional files that support the web application
Adding a Web Service Class to a Web Application Project
To create a web service, perform the following steps to add a web service class to the project:
1. Under the Projects tab in Netbeans (just below the File menu), right click the HugeInteger
project’s node and select New > Web Service… to open the New Web Service dialog.
2. Specify HugeInteger in the Web Service Name field.
3. Specify com.deitel.jhtp7.ch28.hugeinteger in the Package field.
4. Click Finish to dismiss the New Web Service dialog

Dr. P. CHITRALINGAPPA Page 15 of 32


The IDE generates a sample web service class with the name you specified in Step 2. In this class,
you’ll define the methods that your web service makes available to client applications. When you
eventually build your application, the IDE will generate other supporting files (which we’ll discuss shortly)
for your web service

2. Defining the HugeInteger Web Service in Netbeans


// HugeInteger web service that performs operations on large integers.

package com.deitel.jhtp7.ch28.hugeinteger;

import javax.jws.WebService; // program uses the annotation @WebService

import javax.jws.WebMethod; // program uses the annotation @WebMethod

import javax.jws.WebParam; // program uses the annotation @WebParam

@WebService( // annotates the class as a web service

name = "HugeInteger", // sets class name

serviceName = "HugeIntegerService" ) // sets the service name

public class HugeInteger

// write logic here

// WebMethod that adds huge integers represented by String arguments

@WebMethod( operationName = "add" )

public String add( @WebParam( name = "first" ) String first,

@WebParam( name = "second" ) String second ){

// Logic here for addition

// WebMethod that subtracts integers represented by String arguments

@WebMethod( operationName = " subtract" )

public String subtract ( @WebParam( name = "first" ) String first,

@WebParam( name = "second" ) String second ){

// Logic here for subtract

// WebMethod that returns true if first integer is greater than second

@WebMethod( operationName = "bigger" )

public boolean bigger( @WebParam( name = "first" ) String first,

Dr. P. CHITRALINGAPPA Page 16 of 32


@WebParam( name = "second" ) String second ){

// Logic here for bigger

// WebMethod that returns true if first integer is less than second

@WebMethod( operationName = "smaller" )

public boolean smaller ( @WebParam( name = "first" ) String first,

@WebParam( name = "second" ) String second ){

// Logic here for smaller

3. Publishing the HugeInteger Web Service from Netbeans


Netbeans handles all the details of building and deploying a web service for you
– Includes creating the framework required to support the web service
To build project
– Right click the project name in the Netbeans Projects tab
– Select Build Project
To deploy
– Select Deploy Project
– Deploys to the server you selected during application setup
– Also builds the project if it has changed and starts the application server if it is not already
running
To Execute
– Select Run Project
– Also builds the project if it has changed and starts the application server if it is not already
running
To ensure a clean re-build of the entire project

Dr. P. CHITRALINGAPPA Page 17 of 32


– Select Clean Project or Clean and Build Project

4. Testing the HugeInteger Web Service with Sun Java System Application Server’s Tester
Web page
Sun Java System Application Server
– Can dynamically create a Tester web page for testing a web service’s methods from a web
browser
– Enable this feature via the project’s Run options
To display the Tester web page
– Run the web application from NetBeans, or
– Type web service’s URL in browser’s address field followed by ?Tester
Web 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 Netbeans
– To keep it running, launch it independently of Netbeans

Dr. P. CHITRALINGAPPA Page 18 of 32


5. Describing a Web Service with the Web Service Description Language (WSDL)
To consume a web service
– Must know where to find the web service
– Must be provided with the web service’s description
Web Service Description Language (WSDL)
– Describe web services in a platform-independent manner
– The 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
service
To view the WSDL for a web service
– Type URL in the browser’s address field followed by ?WSDL or
– Click the WSDL File link in the Sun Java System Application Server’s Tester web page

Dr. P. CHITRALINGAPPA Page 19 of 32


Consume a Web Service
The web client consumes the Web service according to the service contract. "Consume"
means that the Web service successfully fulfills the web client's request.

1. Creating a Client in Netbeans to Consume the HugeInteger Web Service


Creating a Desktop Application Project in Netbeans 5.5
1. Select File > New Project… to open the New Project dialog.
2. Select General from the Categories list and Java Application from the Projects list.
3. Specify the name UsingHugeInteger in the Project Name field and uncheck the Create

Dr. P. CHITRALINGAPPA Page 20 of 32


Main Class checkbox. In a moment, you’ll add a subclass of JFrame that contains a main
method.
4. Click Finish to create the project.

Adding a Web Service Reference to an Application


To add a web service reference, perform the following steps.
1. Right click the project name (UsingHugeInteger) in the Netbeans Projects tab.
2. Select New > Web Service Client… from the pop-up menu to display the New Web
Service Client dialog (Fig. 28.7).
3. In the WSDL URL field, specify the URL http://localhost:8080/HugeInteger/
HugeIntegerService?WSDL (Fig. 28.7).
4. In the Package field, specify com.deitel.jhtp7.ch28.usinghugeinteger as the package name.
5. Click Finish to dismiss the New Web Service Client dialog.

Fig. 28.7 New Web Service Client dialog

Dr. P. CHITRALINGAPPA Page 21 of 32


2. Consuming the HugeInteger Web Service
To build the client application’s GUI, you must first add a subclass of JFrame to the
project. To do so, perform the following steps:
1. Right click the project name in the Netbeans Project tab.
2. Select New > JFrame Form… to display the New JFrame Form dialog.
3. Specify UsingHugeIntegerJFrame in the Class Name field.
4. Specify com.deitel.jhtp7.ch28.hugeintegerclient in the Package field.
5. Click Finish to close the New JFrame Form dialog.

SOAP (Simple Object Access Protocol)


SOAP (an acronym for Simple Object Access Protocol) is a platform-independent protocol
that uses XML to facilitate remote procedure calls, typically over HTTP. SOAP is one common
protocol for passing information between web service clients and web services. The protocol that
transmits request-and-response messages is also known as the web service’s wire format or wire
protocol, because it defines how information is sent “along the wire.” Each request and response
is packaged in a SOAP message (also known as a SOAP envelope)—an XML “wrapper”
containing the information that a web service requires to process the message. SOAP messages
are written in XML so that they are platform independent.
When a program invokes a web method, the request and all relevant information are
packaged in a SOAP message and sent to the server on which the web service resides. The web
service processes the SOAP message’s contents (contained in a SOAP envelope), which specify
the method that the client wishes to invoke and the method’s arguments. This process of
interpreting a SOAP message’s contents is known as parsing a SOAP message. After the web
service receives and parses a request, the proper method is called with any specified arguments,
and the response is sent back to the client in another SOAP message. The client-side proxy parses
the response, which contains the result of the method call, and returns the result to the client
application.

Dr. P. CHITRALINGAPPA Page 22 of 32


SOAP Message Structure
A SOAP message is an ordinary XML document containing the following elements −
 Envelope − Defines the start and the end of the message. It is a mandatory element.
 Header − Contains any optional attributes of the message used in processing the message,
either at an intermediary point or at the ultimate end-point. It is an optional element.
 Body − Contains the XML data comprising the message being sent. It is a mandatory
element.
 Fault − An optional Fault element that provides information about errors that occur while
processing the message.
<?xml version = "1.0"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV = "http://www.w3.org/2001/12/soap-envelope"
SOAP-ENV:encodingStyle = "http://www.w3.org/2001/12/soap-encoding">
<SOAP-ENV:Header>
...
</SOAP-ENV:Header>
<SOAP-ENV:Body>
...
...
<SOAP-ENV:Fault>
...
...
</SOAP-ENV:Fault>
...
</SOAP-ENV:Body>

</SOAP_ENV:Envelope>

Dr. P. CHITRALINGAPPA Page 23 of 32


SOAP Request

SOAP Response

Dr. P. CHITRALINGAPPA Page 24 of 32


Output:

WSDL (Web services description language)


A web service is an important component in building modern day web applications. Their
main purpose is to allow multiple applications built on various programming languages to talk to
each other.
Web services description language (WSDL) file is again an XML-based file which
basically tells the client application what the web service does. By using the WSDL document, the
client application would be able to understand where the web service is located and how it can be
utilized.
Benefits:
 It is built using the XML programming language. Almost all modern-day technologies
such as .Net and Java have corresponding commands that have the ability to work with
XML. Hence, XML was taken as the most appropriate language for building web services.
 Web services communicate over HTTP. HTTP is a protocol used by all web-based
applications. Hence, it just made sense to ensure that Web services also had the ability to
work over the HTTPprotocol.
 Web services conform to a particular language specification. This specification is set by
the W3C, which is the governing body for all web standards.
 Web services have a description language known as WSDL, which is used to describe the
webservice.
Example:

<!-- WSDL definition structure -->


<definitions
name="hugeinteger" targetNamespace=http://example.org/math/
xmlns=http://schemas.xmlsoap.org/wsdl/>
<!-- abstract definitions -->
<types> ...
<message> ...
<portType> ...

<!-- concrete definitions -->


<binding> ...
<service> ...
</definition>

Dr. P. CHITRALINGAPPA Page 25 of 32


1. <message> - The message parameter in the WSDL definition is used to define the
different data elements for each operation performed by the web service. So in the
example above, we have 2 messages which can be exchanged between the web service
and the client application, one is the "TutorialRequest", and the other is the
"TutorialResponse" operation. The TutorialRequest

contains an element called "TutorialID" which is of the type string. Similarly, the
TutorialResponse operation contains an element called "TutorialName" which is also a
type string.
2. <portType> - This actually describes the operation which can be performed by the web
service, which in our case is called Tutorial. This operation can take 2 messages; one is
an input message, and the other is the output message.
3. <binding> - This element contains the protocol which is used. So in our case, we are
defining it to use http (http://schemas.xmlsoap.org/soap/http). We also specify other
details for the body of the operation, like the namespace and whether the message should
be encoded.

UDDI (Universal Description, Discovery, and Integration)


UDDI is a technology for publishing, querying, finding, and invoking Web services
using a registrythat provides data, metadata, and pointers to these services. The technology builds
on established standards, including Extensible Markup Language (XML) schemas and files,
Simple Object Access Protocol (SOAP) and HTTP messaging, Domain Name System (DNS)
lookup, and Web Services Description Language (WSDL) Web service interface descriptions.
UDDI consists of four parts —
• The UDDI Registry
• The data, metadata, bindings and documents included in the registry
• The UDDI specifications
• Application Programming Interfaces (APIs) and services for publishing to, querying,
and managing information in the Registry.

Dr. P. CHITRALINGAPPA Page 26 of 32


Database driven webservices:
Database drive webserices means WebService with database Mysql.
MySql Database Configuration in NetBeans
Configure MySQL database in the NetBeans IDE and then create the required table into database.

Step 1: Click on the service tab in NetBeans as shown below in Fig 1.

Step 2: Right Click on the DatabasesSelect New Connection as shown below in Fig 2.

Dr. P. CHITRALINGAPPA Page 27 of 32


Step 3: It opens a dialog box for the mysql configuration.-Type the driver name, url , user name
and password as shown below in Fig. 3.

Step 4: Click on the Ok button Now expand the Newly created database connection.

Dr. P. CHITRALINGAPPA Page 28 of 32


It shows the all the tables of the database test as shown below in Fig 4.

Step 5: Create a table named login-->Right Click on the Tables and select Create table as shown
below in Fig 5

Step 6:
 It opens a dialog box for giving the fields name of the table
 Now give the field name and data type as shown below in Fig 6.

Dr. P. CHITRALINGAPPA Page 29 of 32


Step 7: Click on the Ok

Example:
package mypack;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import javax.annotation.Resource;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import javax.sql.DataSource;

@WebService()
public class myaccount {

@Resource(name = "data1") private DataSource data1;

@WebMethod(operationName = "insert")
public String insert(@WebParam(name = "uname") String uname, @WebParam(name = "fname")
String fname,
@WebParam(name = "lname") String lname, @WebParam(name = "location") String location,

@WebParam(name = "phone") String phone, @WebParam(name = "credit") String credit,


@WebParam(name = "dl") String dl) {
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "");
PreparedStatement st =
con.prepareStatement("insert into login values(?,?,?,?,?,?,?)");

Dr. P. CHITRALINGAPPA Page 30 of 32


st.setString(1, uname); st.setString(2, fname); st.setString(3, lname); st.setString(4, location);
int ph = Integer.parseInt(phone); st.setInt(5, ph);
int cr = Integer.parseInt(credit); st.setInt(6, cr);
int d1 = Integer.parseInt(dl); st.setInt(7, d1); st.executeUpdate();
} catch (Exception e) { System.out.println(e.getMessage());
}
return "record inserted";
}
}

Step:
• Now deploy the project
• Right click on the project
• Select Undeploy and Deploy.
• It builds and deploys the MyAccount Web project on the glassfish server.
• After deploying now we can test the Web Service created
• Right click on the myaccount webservice
• Select Test Web Service as shown below in Fig.

Dr. P. CHITRALINGAPPA Page 31 of 32


Why Ajax is called Asynchronous JavaScript and XML?

AJAX, which stands for asynchronous JavaScript and XML, is a technique that allows
web pages to be updated asynchronously, which means that the browser doesn't need to reload the
entire page when only a small bit of data on the page has changed. AJAX passes only the updated
information to and from the server.

AJAX can access the server both synchronously and asynchronously:


 Synchronously, in which the script stops and waits for the server to send back a
replybefore continuing.
 Asynchronously, in which the script allows the page to continue to be processed
and handles the reply if and when it arrives.
Therefore, the preferred way to use AJAX is to use asynchronous calls wherever possible.
This is the default setting in AJAX.

Dr. P. CHITRALINGAPPA Page 32 of 32

You might also like