Unit 4
Unit 4
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
application –SOAP.
Ajax - Asynchronous
JavaScript What is Ajax?
Asynchronous JavaScript and XML or Ajax for short is new web development
technique used for the development of most interactive website. Ajax helps in making web
application more interactive by retrieving small amount of data from web server and then
showing it on application without refreshing our page
Usually in all the web applications, the user enters the data into the form and then clicks on the
submit button to submit the request to the server. Server processes the request and returns the
view in new page (by reloading the whole page). This process is inefficient, time consuming,
and a little frustrating for you user if the only the small amount of data exchange is required.
For example in an user registration form, this can be frustrating thing for the user, as whole
page is reloaded only to check the availability of the user name. Ajax will help in making your
application more interactive. With the help of Ajax you can tune your application to check the
availability of the user name without refreshing the whole page.
JavaScript:
JavaScript is used to make a request to the web server. Once the response is returned by
the web server, more JavaScript can be used to update the current page. DHTML and
CSS is used to show the output to the user. JavaScript is used very heavily to provide the
dynamic behavior to the application.
come back. User can do the normal work without any problem.
XML:
XML may be used to receive the data returned from the web server. JavaScript can be
used to process the XML data returned from the web server easily.
When user first visits the page, the Ajax engine is initialized and loaded. From that point of
time user interacts with Ajax engine to interact with the web server. The Ajax engine operates
asynchronously while sending the request to the server and receiving the response from server.
Ajax life cycle within the web browser can be divided into following stages:
User Visit to the page: User visits the URL by typing URL in browser or clicking a
link from some other page.
2
UNIT V INTRODUCTION TO AJAX and WEB SERVICES
Benefits of Ajax
Ajax is new very promising technology, which has become extremely popular these days.
Here are the benefits of using Ajax:
Ajax can be used for creating rich, web-based applications that look and works like
a desktop application
Ajax is easy to learn. Ajax is based on JavaScript and existing technologies like
XML, CSS, DHTML. etc. So, its very easy to learn Ajax
Ajax can be used to develop web applications that can update the page data
continuously without refreshing the whole page
AJAX is playing a crucial role in making Web 2.0 promises a reality. Some of the features
of web 2.0 are
a) Use of Web as the platform
b) Software delivered as a service instead of packaged software
c) Cost-effective scalability
d) Architecture with user participation
AJAX interfaces are a key component of many Web 2.0 applications. Google, Yahoo,
Microsoft, Amazon and many others have embraced AJAX.
Google services like Maps, Gmail, Suggest, Reader use it. Google Maps, which is considered
as one of the most impressive and popular AJAX based application, allows user to zoom in
and out and scroll the map in four directions very much like a desktop application. User can
drag the map on screen with the mouse pointer and double click to center. All this with no
clicking and waiting for graphics to reload each time you want to view the adjacent parts of a
map. Gmail uses AJAX for spell-check, auto save, new email check and other functions. In
Google suggest suggestions are provided in real time as the user types the search query.
Yahoo's Flickr and instant search use AJAX. In Flickr the text-editing and tagging interface
uses it. Instant search gives user the result as he/she is typing the query. Yahoo frontpage too
has been AJAXified.
UNIT V INTRODUCTION TO AJAX and WEB SERVICES
5
UNIT V INTRODUCTION TO AJAX and WEB SERVICES
Windows Live is a free AJAX virtual desktop. Some of its features are search, news, maps,
email integration, instant messenger, contact management tool etc. More features can be
included through the use of third party 'Gadgets'.
Meebo is a web based instant messenger client, it supports Yahoo, Gtalk, MSN and AIM
protocols. Writely, Zoho, gOffice, AjaxOffice are AJAX based online word processors; some
are full-fledged office suits. Digg is a technology news website that combines social
bookmarking, blogging, RSS, and non-hierarchical editorial control. Travbuddy lets users
create travel journals and share travel experiences, reviews and photos. This application also
uses Google Maps. Pageflakes, Netvibes and Protopage are free startpages.
Zimbra is an AJAX based collaboration suit. Kiko and Calendarhub are online calendars.
Pixoh is an online photo editing application
Here is the main principle: the server no longer manages the whole page but only sends raw data
to the client; all the pages generation and user interactions management is done on the client
side, that is to say in the browser.
5
UNIT V INTRODUCTION TO AJAX and WEB SERVICES
6
UNIT V INTRODUCTION TO AJAX and WEB SERVICES
On the first diagram, the Web application is mainly executed on the server side. It sends directly
to the browser HTML pages, CSS and possibly JavaScript enhancing the behavior. Then, for
each user action requiring new data, the server is queried and returns a whole new HTML page.
The second diagram introduces the AJAX pattern, for Asynchronous JavaScript and XML,
which appeared in the mid-2000s).
This architecture principle can make the application more responsive by reducing exchanges
between browser and server. When a user action generates a client call to retrieve new data, the
server only returns view fragments. Thus, only a small part of the screen is refreshed, rather than
the entire page. This requires the development of client-side JavaScript in order to manage
partial refreshments, for example by using the jQuery library and its $.Ajax function or others
tools more integrated with server platforms (such as Java Server Faces or Google Web Toolkit
for Java environments).
This architecture brought more reactivity but also more complexity. It has many pitfalls:
the extensive use of jQuery can make impossible the application maintenance,
without implementing complex technical rules (offered today by MV* frameworks like
Backbone.js and AngularJS)
despite their aim to ease developments, server-side frameworks like Java Server
Faces turned out to be very heavy and complex, leading to many bugs and
performance issues.
The third diagram shows the new MV* client-side architecture, whose principle disrupts with
the previous ones: now the server sends only raw unformatted data and the client is
responsible for generating the screen out of it.
The term MV* refers to the MVC pattern, for Model View Controller, widely used server-side to
separate data and views management. More and more we use this term MV*, in order to
highlight the little differences from pure MVC implementations. But this is an expert
discussion…
9
UNIT V INTRODUCTION TO AJAX and WEB SERVICES
The important point in this new architecture is the shift of all the UI logic from the server to
the client.
This separation of concerns between server and client is not a new phenomenon. It has been
taken back by native mobile applications, consuming APIs independent from the client. The new
Web application architectures bring this possibility to Web applications.
The industrialization is also driven by the fact that JavaScript is spreading overother
areas than just Web applications, especially server-side with node.js.
10
UNIT V INTRODUCTION TO AJAX and WEB SERVICES
1. JavaScript
2. XML
3. CSS
4. W3C DOM
5. XMLHttpRequest
Since it embraces so many technologies that's why it is neither easy nor tough. In AJAX,
"A"stands for "Asynchronous" that means sending data from the browser and
response send back from the server are not sequential. When user make requests then the
server can do its own work or it may fulfill other requests. Similarly when server is busy in
responding user may make further requests that means no request or response is synchronous
or depending on each other.
Data Exchange in AJAX
XML: In AJAX, data is exchanged with the help of XML files, there are many alternate
techniques are also available like CSV, JSON etc.
11
UNIT V INTRODUCTION TO AJAX and WEB SERVICES
Because of the simplicity of XML, it is becoming the new standard of exchanging data
between server and browser. XML is very easy to reformat, reuse.
DOM: The DOM (Document Object Model) is the object oriented representation of XML &
HTML documents, and provides an API for changing the content, structure, and style. The
DOM represents HTML & XML documents as object hierarchy, which is easy to parse by
XML tools.
CSS: CSS (Cascading Style Sheet) is used in web site for designing purpose, we can use CSS
in almost all aspects of the way the web pages look, size, color, width, length etc. of text box,
input area,..etc. that means every attribute of every user interface. In AJAX it is very usefulto
use CSS, you can implement CSS as color changing on validation checking in
a registration form and other.
XMLHttpRequest: Unlike other usual web pages, with AJAX, JavaScript communicates
with server using JavaScript's XMLHttpRequest object. With the help of XMLHttpRequest a
web page can send request and get a response from the server without refreshing the page.
This object is supported by all the leading web browsers.
JavaScript: We can say that JavaScript is the pivot point of AJAX . IT performs the following
role in AJAX:
XMLHttpRequest Object:
As the use of XML and web services is increasing day by day, it is good to connect an HTML
page with XML, with the help of that we can get interim updates so easily without reloading
the page. It is possible due to the XMLHttpRequest object, which is responsible for retrieving
and submitting the XML data directly from the client side. It relies on Document Object
Model (DOM) to convert the retrieved XML data into HTML.
Microsoft first implemented the XMLHttpRequest object in IE 5 for Windows as an ActiveX
object. Afterward Mozilla and Apple's Safari also implemented in their own style.
XMLHttpRequest object facilitates the web developer a lot because with the help of this object
you can update the page with new data without reloading the page, communicate with server
in the background, request and receive data from the web server.
10
UNIT V INTRODUCTION TO AJAX and WEB SERVICES
We can create an instance of the XMLHttpRequest in most of the modern popular browsers,
and in the old versions of the browsers we need to create an object of ActiveXObject.
var xmlobj=new XMLHttpRequest ();
var activeobj=new ActiveXObject("Microsoft.XMLHTTP");
We need to create an XMLHttpRequest, after that we will use few important functions like:
11
UNIT V INTRODUCTION TO AJAX and WEB SERVICES
2. readystate property: readystate property holds the state of the server response, every
time readystate property change , onreadystatechange function executes. Possible values
and their meaning are given below:
3. responseText property: The data sent back from the server is stored and retrieved later
with the help of responseText property.
AJAX Example
In the following example we will see how to display server IP address dynamically with the
help of AJAX, HTML, & PHP.
SimpleAjax.html
<html>
<body>
<script type="text/javascript" >
function ajaxfunction()
{
var xmlhttp;
if(window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)
{
document.timeform.time.value=xmlhttp.responseText;
12
UNIT V INTRODUCTION TO AJAX and WEB SERVICES
}
}
xmlhttp.open("GET","SimpleAjax.php",true);
xmlhttp.send(null);
}
</script>
<form name="timeform" >
Name:<input type="text" name="Name" onkeyup="ajaxfunction()"; />
<br/>
Time:<input type="text" name="time"/>
</form>
</body>
</html>
SimpleAjax.php
<?php
echo ($SERVER_ADDR);
?>
SimpleAjax.html
<html>
<body>
<script type="text/javascript" >
function ajaxfunction()
{
var xmlhttp;
if(window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)
{
13
UNIT V INTRODUCTION TO AJAX and WEB SERVICES
document.timeform.time.value=xmlhttp.responseText;
}
}
xmlhttp.open("GET","SimpleAjax.php",true);
xmlhttp.send(null);
}
</script>
<form name="timeform" >
Name:<input type="text" name="Name" onkeyup="ajaxfunction()"; />
<br/>
Time:<input type="text" name="time"/>
</form>
</body>
</html>
Note: In this way we can get different dynamic values of server and other like time, date
etc.
The server side script is developed in PHP that displays the current time of the server. You
modify thephp to display your own message. This program can also be used to do some
business processing.
These days Ajax is being used extensively for the development of interactive websites. There
are many frameworks available these days to develop Ajax applications. But you should start
learning the Ajax from scratch. This is the first example in Ajax that will give you quickstart
in the Ajax technologies.
Let's get started with the Ajax technology and develop our fist Ajax Datetime example.
<html>
14
UNIT V INTRODUCTION TO AJAX and WEB SERVICES
<head>
<title>Ajax Example</title>
<script language="Javascript">
function postRequest(strURL) {
var xmlHttp;
} else if (window.ActiveXObject) { // IE
xmlHttp.setRequestHeader('Content-Type',
'application/x-www-form-urlencoded');
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
updatepage(xmlHttp.responseText);
xmlHttp.send(strURL);
function updatepage(str){
document.getElementById("result").innerHTML =
"<font color='red' size='5'>" + str + "</font>";;
15
UNIT V INTRODUCTION TO AJAX and WEB SERVICES
function showCurrentTime(){
var url="time.php?id="+rnd;
postRequest(url);
</script>
</head>
<body>
current date and time from server and shows on the form. To view the current
<form name="f1">
</form>
<div id=result></div>
</body>
</html>
16
UNIT V INTRODUCTION TO AJAX and WEB SERVICES
When use clicks on the "Show Time" button, the showCurrentTime() is called. The
the function showCurrentTime() calls the time.php using Ajax and then updates the
time values retrieved from server.
Here is the code of PHP (time.php) file:
<?
print date("l M dS, Y,
H:i:s");
?>
17
UNIT V INTRODUCTION TO AJAX and WEB SERVICES
in the 'multiply.php' page at serverside. The 'callmultiply()' sends the numbers as url
string by calling the 'postRequest()' method. The 'postRequest()' method generates
Ajax call to serverside script 'multiply.php'. And finally 'updatepage()' method
updates the multiplication result on the html page.
function updatepage(str){
document.getElementById('result').value = str;
}
function callMultiply(){
var a = parseInt(document.f1.a.value);
18
UNIT V INTRODUCTION TO AJAX and WEB SERVICES
var b = parseInt(document.f1.b.value);
var url = "multiply.php?a=" + a + "&b=" + b + "";
postRequest(url);
}
</script>
</head>
<body>
<h1 align="center"><font color="#000080">Ajax Example</font></h1>
<form name="f1">
<input name="a" id="a" value="">
<input name="b" id="b" value="">
<input name="result" type="text" id="result">
<input type="button" value="Multiply" onClick="callMultiply()"
name="showmultiply">
</form>
</body>
</html>
19
UNIT V INTRODUCTION TO AJAX and WEB SERVICES
Web services
Web service is any piece of software that makes itself available over the internet and
uses a standardized XML messaging system. XML is used to encode all communications
to a web service. For example, a client invokes a web service by sending an XML
message, then waits for a corresponding XML response. Because all communication is in
XML, web services are not tied to any one operating system or programming language--
Java can talk with Perl; Windows applications can talk with Unix applications.
Web Services are self-contained, modular, distributed, dynamic applications that can be
described, published, located, or invoked over the network to create products, processes,
20
UNIT V INTRODUCTION TO AJAX and WEB SERVICES
and supply chains. These applications can be local, distributed, or Web-based. Web
services are built on top of open standards such as TCP/IP, HTTP, Java, HTML, and
XML.
Web services are XML-based information exchange systems that use the Internet for
direct application-to-application interaction. These systems can include programs,
objects, messages, or documents.
A web service is a collection of open protocols and standards used for exchanging data
between applications or systems. Software applications written in various programming
languages and running on various platforms can use web services to exchange data over
computer networks like the Internet in a manner similar to inter-process communication
on a single computer. This interoperability (e.g., between Java and Python, or Windows
and Linux applications) is due to the use of open standards
31
UNIT V INTRODUCTION TO AJAX and WEB SERVICES
The basic Web services platform is XML + HTTP. All the standard Web Services works
using following components
We can build a Java-based Web Service on Solaris that is accessible from your Visual
Basic program that runs on Windows. We can also use C# to build new Web Services on
Windows that can be invoked from your Web application that is based on JavaServer Pages
(JSP) and runs on Linux.
An Example
The processing logic for this system is written in Java and resides on a Solaris machine, which
also interacts with a database to store the information.
1. The client program bundles the account registration information into a SOAPmessage.
2. This SOAP message is sent to the Web Service as the body of an HTTP POST request.
3. The Web Service unpacks the SOAP request and converts it into a command that the
application can understand. The application processes the information as required and
responds with a new unique account number for that customer.
4. Next, the Web Service packages up the response into another SOAP message, which it
sends back to the client program in response to its HTTP request.
5. The client program unpacks the SOAP message to obtain the results of the account
registration process. For further details regarding the implementation of Web Services
technology, read about the Cape Clear product set and review the product components.
A Web service is a unit of managed code that can be remotely invoked using
HTTP, that is, it can be activated using HTTP requests. So, Web Services allows you to
expose the functionality of your existing code over the network. Once it is exposed on the
network, other application can use the functionality of your program.
Web Services allows different applications to talk to each other and share data
and services among themselves. Other applications can also use the services of the web
services. For example VB or .NET application can talk to java web services and vice
33
UNIT V INTRODUCTION TO AJAX and WEB SERVICES
versa. So, Web services are used to make the application platform and technology
independent.
Standardized Protocol:
Web Services uses standardized industry standard protocol for the communication. All
the four layers (Service Transport, XML Messaging, Service Description and Service
Discovery layers) use the well defined protocol in the Web Services protocol stack. This
standardization of protocol stack gives the business many advantages like wide range of
choices, reduction in the cost due to competition and increase in the quality.
Low Cost of communication:
Web Services uses SOAP over HTTP protocol for the communication, so you can
use your existing low cost internet for implementing Web Services. This solution is much
less costly compared to proprietary solutions like EDI/B2B. Beside SOAP over HTTP,
Web Services can also be implemented on other reliable transport mechanisms like FTP
etc.
Web Services uses XML at data representation and data transportation layers. Using
XML eliminates any networking, operating system, or platform binding. So Web
Services based applications are highly interoperable application at their core level.
Loosely coupled
A consumer of a web service is not tied to that web service directly. The web
service interface can change over time without compromising the client's ability to
interact with the service. A tightly coupled system implies that the client and server logic
are closely tied to one another, implying that if one interface changes, the other must also
be updated. Adopting a loosely coupled architecture tends to make software systems
more manageable and allows simpler integration between different systems.
Coarse-grained
34
UNIT V INTRODUCTION TO AJAX and WEB SERVICES
Synchronicity refers to the binding of the client to the execution of the service. In
synchronous invocations, the client blocks and waits for the service to complete its
operation before continuing. Asynchronous operations allow a client to invoke a service
and then execute other functions. Asynchronous clients retrieve their result at a later point
in time, while synchronous clients receive their result when the service has completed.
Asynchronous capability is a key factor in enabling loosely coupled systems.
The first is to examine the individual roles of each web service actor.
The second is to examine the emerging web service protocol stack.
There are three major roles within the web service architecture:
Service provider:
35
UNIT V INTRODUCTION TO AJAX and WEB SERVICES
This is the provider of the web service. The service provider implements the service and
makes it available on the Internet.
Service requestor
This is any consumer of the web service. The requestor utilizes an existing web service
by opening a network connection and sending an XML request.
Service registry
This is a logically centralized directory of services. The registry provides a central place
where developers can publish new services or find existing ones. It therefore serves as a
centralized clearinghouse for companies and their services.
A second option for viewing the web service architecture is to examine the emerging web service
protocol stack. The stack is still evolving, but currently has four main layers.
Service transport
This layer is responsible for transporting messages between applications. Currently, this
layer includes hypertext transfer protocol (HTTP), Simple Mail Transfer Protocol
(SMTP), file transfer protocol (FTP), and newer protocols, such as Blocks Extensible
Exchange Protocol (BEEP).
XML messaging
This layer is responsible for encoding messages in a common XML format so that
messages can be understood at either end. Currently, this layer includes XML-RPC and
SOAP.
Service description
This layer is responsible for describing the public interface to a specific web service.
Currently, service description is handled via the Web Service Description Language
(WSDL).
Service discovery
This layer is responsible for centralizing services into a common registry, and providing
easy publish/find functionality. Currently, service discovery is handled via Universal
Description, Discovery, and Integration (UDDI).
36
UNIT V INTRODUCTION TO AJAX and WEB SERVICES
As web services evolve, additional layers may be added, and additional technologies may
Service Transport
The bottom of the web service protocol stack is service transport. This layer is responsible for
actually transporting XML messages between two computers.
Currently, HTTP is the most popular option for service transport. HTTP is simple, stable,
and widely deployed. Furthermore, most firewalls allow HTTP traffic. This allows
XMLRPC or SOAP messages to masquerade as HTTP messages. This is good if you
want to easily integrate remote applications, but it does raise a number of security
concerns.
SOAP
Although SOAP can be used in a variety of messaging systems and can be delivered via a variety
of transport protocols, the initial focus of SOAP is remote procedure calls transported via HTTP.
37
UNIT V INTRODUCTION TO AJAX and WEB SERVICES
SOAP enables client applications to easily connect to remote services and invoke remote methods.
Other frameworks, including CORBA, DCOM, and Java RMI, provide similar functionality to
SOAP, but SOAP messages are written entirely in XML and are therefore uniquely platform-
and language-independent.
Envelope: ( Mandatory )
Defines the start and the end of the message.
Header: ( Optional )
Contains any optional attributes of the message used in processing the message, either at
an intermediary point or at the ultimate end point.
Body: ( Mandatory )
Contains the XML data comprising the message being sent.
Fault: ( Optional )
An optional Fault element that provides information about errors that occurred 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>
SOAP Envelope Element
38
UNIT V INTRODUCTION TO AJAX and WEB SERVICES
The SOAP envelope indicates the start and the end of the message so that the receiver knows
when an entire message has been received. The SOAP envelope solves the problem of knowing
when you're done receiving a message and are ready to process it. The SOAP envelope is
therefore basic ally a packaging mechanism
<?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:Envelope>
Following example illustrates the use of a SOAP message within an HTTP POST operation,
which sends the message to the server. It shows the namespaces for the envelope schema
39
UNIT V INTRODUCTION TO AJAX and WEB SERVICES
definition and for the schema definition of the encoding rules. The OrderEntry reference in the
HTTP header is the name of the program to be invoked at the tutorialspoint.com Web site.
Host: www.tutorialspoint.com
Content-Length: nnnn
<?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:Envelope>
The optional Header element offers a flexible framework for specifying additional application-
level requirements. For example, the Header element can be used to specify a digital signature
for password-protected services; likewise, it can be used to specify an account number for pay-
per- use SOAP services.
40
UNIT V INTRODUCTION TO AJAX and WEB SERVICES
Actor attribute:
The SOAP protocol defines a message path as a list of SOAP service nodes. Each of
these intermediate nodes can perform some processing and then forward the message to
the next node in the chain. By setting the Actor attribute, the client can specify the
recipient of the SOAP header.
MustUnderstand attribute
Indicates whether a Header element is optional or mandatory. If set to true ie. 1 the
recipient must understand and process the Header attribute according to its defined
semantics, or return a fault.
<?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>
<t:Transaction
xmlns:t="http://www.tutorialspoint.com/transaction/"
SOAP-ENV:mustUnderstand="true">5</t:Transaction>
</SOAP-ENV:Header>
...
...
</SOAP-ENV:Envelope>
The SOAP body is a mandatory element which contains the application-defined XML data being
exchanged in the SOAP message. The body must be contained within the envelope and must
follow any headers that might be defined for the message. The body is defined as a child element
of the envelope, and the semantics for the body are defined in the associated SOAP schema.
41
UNIT V INTRODUCTION TO AJAX and WEB SERVICES
The body contains mandatory information intended for the ultimate receiver of the message. For
example:
<?xml version="1.0"?>
<SOAP-ENV:Envelope
........
<SOAP-ENV:Body>
<m:GetQuotation xmlns:m="http://www.tp.com/Quotation">
<m:Item>Computers</m:Item>
</m:GetQuotation>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
The example above requests the quotation of computer sets. Note that the m:GetQuotation and
the Item elements above are application-specific elements. They are not a part of the SOAP
standard.
<?xml version="1.0"?>
<SOAP-ENV:Envelope
........
<SOAP-ENV:Body>
<m:GetQuotationResponse xmlns:m="http://www.tp.com/Quotation">
<m:Quotation>This is Qutation</m:Quotation>
42
UNIT V INTRODUCTION TO AJAX and WEB SERVICES
</m:GetQuotationResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
Normally, the application also defines a schema to contain semantics associated with the request
and response elements.
The Quotation service might be implemented using an EJB running in an application server; if
so, the SOAP processor would be responsible for mapping the body information as parameters
into and out of the EJB implementation of theGetQuotationResponse service. The SOAP
processor could also be mapping the body information to a .NET object, a CORBA object, a
COBOL program, and so on.
When an error occurs during processing, the response to a SOAP message is a SOAP fault
element in the body of the message, and the fault is returned to the sender of the SOAP message.
The SOAP fault mechanism returns specific information about the error, including a predefined
code, a description, the address of the SOAP processor that generated
Sub Element
Description
<faultCode>
A text code used to indicate a class of errors. See the next Table for a listing of predefined fault
codes.
<faultString>
43
UNIT V INTRODUCTION TO AJAX and WEB SERVICES
<faultActor>
A text string indicating who caused the fault. This is useful if the SOAP message travels through
several nodes in the SOAP message path, and the client needs to know which node caused the
error. A node that does not act as the ultimate destination must include a faultActor element.
<detail>
An element used to carry application-specific error messages. The detail element can contain
child elements, called detail entries.
The faultCode values defined below must be used in the faultcode element when describing faults
Error
Description
SOAP-ENV:VersionMismatch
SOAP-ENV:MustUnderstand
An immediate child element of the Header element, with the mustUnderstand attribute set to
"1", was not understood
SOAP-ENV:Client
SOAP-ENV:Server
There was a problem with the server so the message could not proceed
The following code is a sample Fault. The client has requested a method named
ValidateCreditCard , but the service does not support such a method. This represents a client
request error, and the server returns the following SOAP response:
44
UNIT V INTRODUCTION TO AJAX and WEB SERVICES
<SOAP-ENV:Envelope
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/1999/XMLSchema">
<SOAP-ENV:Body>
<SOAP-ENV:Fault>
<faultcode xsi:type="xsd:string">SOAP-ENV:Client</faultcode>
<faultstring xsi:type="xsd:string">
Failed to locate method (ValidateCreditCard) in class
(examplesCreditCard) at /usr/local/ActivePerl-5.6/lib/
site_perl/5.6.0/SOAP/Lite.pm line 1555.
</faultstring>
</SOAP-ENV:Fault>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
SOAP Encoding
SOAP includes a built-in set of rules for encoding data types.This enables the SOAP
message to indicate specific data types, such as integers, floats, doubles, or arrays.
SOAP data types are divided into two broad categories: scalar types and compound types.
Scalar types contain exactly one value, such as a last name, price, or product description.
Compound types contain multiple values, such as a purchase order or a list of stock quotes.
Compound types are further subdivided into arrays and structs.
The encoding style for a SOAP message is set via the SOAP-ENV:encodingStyle attribute.
SOAP arrays have a very specific set of rules, which require that you specify both the
element type and array size. SOAP also supports multidimensional arrays, but not all
SOAP implementations support multidimensional functionality.
SOAP Transport
SOAP requests are sent via an HTTP request and SOAP responses are returned within the
content of the HTTP response. While SOAP requests can be sent via an HTTP GET, the
specification includes details on HTTP POST only.
Additionally, both HTTP requests and responses are required to set their content type to text/xml.
The SOAP specification mandates that the client must provide a SOAPAction header, but the
actual value of the SOAPAction header is dependent on the SOAP server implementation.
SOAP Examples
In the example below, a GetQuotation request is sent to a SOAP Server over HTTP. The request
has a QuotationName parameter, and a Quotation will be returned in the response.
Host: www.xyz.org
8 Content-Length: nnn
<?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:Body xmlns:m="http://www.xyz.org/quotations">
<m:GetQuotation>
<m:QuotationsName>MiscroSoft</m:QuotationsName>
46
UNIT V INTRODUCTION TO AJAX and WEB SERVICES
</m:GetQuotation>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
HTTP/1.0 200 OK
8 Content-Length: nnn
<?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:Body xmlns:m="http://www.xyz.org/quotation">
<m:GetQuotationResponse>
</m:GetQuotationResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
47
UNIT V INTRODUCTION TO AJAX and WEB SERVICES
WSDL Usage:
WSDL is often used in combination with SOAP and XML Schema to provide web services over
the Internet. A client program connecting to a web service can read the WSDL to determine what
functions are available on the server. Any special datatypes used are embedded in the WSDL file
in the form of XML Schema. The client can then use SOAP to actually call one of the functions
listed in the WSDL.
WSDL Elements
WSDL breaks down Web services into three specific, identifiable elements that can be combined
or reused once defined.
Three major elements of WSDL that can be defined separately and they are:
Types
Operations
48
UNIT V INTRODUCTION TO AJAX and WEB SERVICES
Binding
A WSDL document has various elements, but they are contained within these three main
elements, which can be developed as separate documents and then they can be combined or
reused to form complete WSDL files.
Following are the elements of WSDL document. Within these elements are further subelements,
or parts:
Definition: element must be the root element of all WSDL documents. It defines the
name of the web service, declares multiple namespaces used throughout the remainder of
the document, and contains all the service elements described here.
Data types: the data types - in the form of XML schemas or possibly some other
mechanism - to be used in the messages
Message: an abstract definition of the data, in the form of a message presented either as
an entire document or as arguments to be mapped to a method invocation.
Operation: the abstract definition of the operation for a message, such as naming a
method, message queue, or business process, that will accept and process the message
Port type : an abstract set of operations mapped to one or more end points, defining the
collection of operations for a binding; the collection of operations, because it is abstract,
can be mapped to multiple transports through various bindings.
Binding: the concrete protocol and data formats for the operations and messages defined
for a particular port type.
Port: a combination of a binding and a network address, providing the target address of
the service communication.
Service: a collection of related end points encompassing the service definitions in the
file; the services map the binding to the port and include any extensibility definitions.
In addition to these major elements, the WSDL specification also defines the following utility
elements:
<definitions>
<types>
definition of types........
</types>
49
UNIT V INTRODUCTION TO AJAX and WEB SERVICES
<message>
definition of a message....
</message>
<portType>
<operation>
definition of a operation.......
</operation>
</portType>
<binding>
definition of a binding....
</binding>
<service>
definition of a service....
</service>
</definitions>
A WSDL document can also contain other elements, like extension elements and a service
element that makes it possible to group together the definitions of several web services in one
single WSDL document.
Patterns of Operation
One-way :
The service receives a message. The operation therefore has a single inputelement. The grammar
for a one-way operation is:
The service receives a message and sends a response. The operation therefore has
one input element, followed by one output element. To encapsulate errors, an
50
UNIT V INTRODUCTION TO AJAX and WEB SERVICES
optional fault element can also be specified. The grammar for a request-response operation is:
<wsdl:definitions.....>
<wsdl:portType.....> *
<wsdl:operation name="nmtoken" parameterOrder="nmtokens">
<wsdl:input name="nmtoken"? message="qname"/>
<wsdl:output name="nmtoken"? message="qname"/>
51
UNIT V INTRODUCTION TO AJAX and WEB SERVICES
The service sends a message and receives a response. The operation therefore has
one output element, followed by one input element. To encapsulate errors, an
optional fault element can also be specified. The grammar for a solicit-response operation is:
<wsdl:definitions.....>
<wsdl:portType.....> *
<wsdl:operation name="nmtoken" parameterOrder="nmtokens">
<wsdl:output name="nmtoken"? message="qname"/>
<wsdl:input name="nmtoken"? message="qname"/>
<wsdl:fault name="nmtoken" message="qname"/>*
</wsdl:operation>
</wsdl:portType >
</wsdl:definitions>
Notification :
The service sends a message. The operation therefore has a single outputelement. Following is
the grammer for a notification operation:
<wsdl:definitions.....>
<wsdl:portType.....> *
<wsdl:operation name="nmtoken">
<wsdl:output name="nmtoken"? message="qname"/>
</wsdl:operation>
</wsdl:portType >
</wsdl:definitions>
The <binding> element provides specific details on how a portType operation will
actually be transmitted over the wire.
The bindings can be made available via multiple transports, including HTTP GET, HTTP
POST, or SOAP.
The bindings provide concrete information on what protocol is being used to transfer
portType operations.
The bindings provide information where the service is located.
For SOAP protocol, the binding is <soap:binding>, and the transport is SOAP messages
on top of HTTP protocol.
52
UNIT V INTRODUCTION TO AJAX and WEB SERVICES
The binding element has two attributes - the name attribute and the type attribute.
The name attribute defines the name of the binding, and the type attribute points to the port for
the binding, in this case the "tns:Hello_PortType" port.
SOAP Binding
WSDL 1.1 includes built-in extensions for SOAP 1.1. This enables you to specify SOAPspecific
details, including SOAP headers, SOAP encoding styles, and the SOAPAction HTTP header.
The SOAP extension elements include:
This element indicates that the binding will be made available via SOAP. The styleattribute
indicates the overall style of the SOAP message format. A style value of rpc specifies an RPC
format.
The transport attribute indicates the transport of the SOAP messages. The value
http://schemas.xmlsoap.org/soap/http indicates the SOAP HTTP transport, whereas
http://schemas.xmlsoap.org/soap/smtp indicates the SOAP SMTP transport.
soap:operation
This element indicates the binding of a specific operation to a specific SOAP implementation.
The soapAction attribute specifies that the SOAPAction HTTP header be used for identifying the
service.
soap:body
This element enables you to specify the details of the input and output messages. In the case of
HelloWorld, the body element specifies the SOAP encoding style and the namespace URN
associated with the specified service.
<soap:body
encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
namespace="urn:examples:helloservice"
use="encoded"/>
</input>
<output>
<soap:body
encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
namespace="urn:examples:helloservice"
use="encoded"/>
</output>
</operation>
</binding>
A <port> element defines an individual endpoint by specifying a single address for a binding.
<wsdl:definitions.....>
<wsdl:service.....> *
</wsdl:port>
</wsdl:service>
</wsdl:definitions>
The port element has two attributes - the name attribute and the binding attribute.
The name attribute provides a unique name among all ports defined within in the
enclosing WSDL document.
The binding attribute refers to the binding using the linking rules defined by WSDL.
Binding extensibility elements (1) are used to specify the address information for the port.
A port MUST NOT specify more than one address.
A port MUST NOT specify any binding information other than address information.
58
UNIT V INTRODUCTION TO AJAX and WEB SERVICES
<service name="Hello_Service">
<soap:address
location="http://www.examples.com/SayHello/">
</port>
</service>
The <service> element defines the ports supported by the Web service. For each of the
supported protocols, there is one port element. The service element is a collection of
ports.
Web service clients can learn from the service element where to access the service,
through which port to access the Web service, and how the communication messages are
defined.
The service element includes a documentation element to provide human-readable
documentation.
<service name="Hello_Service">
<soap:address
location="http://www.examples.com/SayHello/">
</port>
</service>
The binding attributes of por element associate the address of the service with a binding element
defined in the Web service. In this example this is Hello_Binding
59
UNIT V INTRODUCTION TO AJAX and WEB SERVICES
<soap:binding style="rpc"
transport="http://schemas.xmlsoap.org/soap/http"/>
<operation name="sayHello">
<soap:operation soapAction="sayHello"/>
<input>
<soap:body
encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
namespace="urn:examples:helloservice"
use="encoded"/>
</input>
<output>
<soap:body
encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
namespace="urn:examples:helloservice"
use="encoded"/>
</output>
</operation>
</binding>
60