Você está na página 1de 39

UNIT V

INTRODUCTION TO AJAX and WEB SERVICES


9
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.
5.1 AJAX: AJAX CLIENT SERVER ARCHITECTURE

AJAX stands for Asynchronous JavaScript and XML. AJAX is a new technique for creating better, faster, and more
interactive web applications with the help of XML, HTML, CSS, and Java Script.

Ajax uses XHTML for content, CSS for presentation, along with Document Object Model and JavaScript for dynamic
content display.

Conventional web applications transmit information to and from the server using synchronous requests. It means you
fill out a form, hit submit, and get directed to a new page with new information from the server.

With AJAX, when you hit submit, JavaScript will make a request to the server, interpret the results, and update the
current screen. In the purest sense, the user would never know that anything was even transmitted to the server.

XML is commonly used as the format for receiving server data, although any format, including plain text, can be used.

AJAX is a web browser technology independent of web server software.

A user can continue to use the application while the client program requests information from the server in the
background.

Intuitive and natural user interaction. Clicking is not required, mouse movement is a sufficient event trigger.

Data-driven as opposed to page-driven.

AJAX is Based on Open Standards


AJAX is based on the following open standards:

Browser-based presentation using HTML and Cascading Style Sheets (CSS).

Data is stored in XML format and fetched from the server.

Behind-the-scenes data fetches using XMLHttpRequest objects in the browser.

JavaScript to make everything happen.

5.2 XML HTTP REQUEST OBJECT


The XMLHttpRequest Object
All modern browsers support the XMLHttpRequest object.
The XMLHttpRequest object is used to exchange data with a server behind the scenes. This means that it is possible to update
parts of a web page, without reloading the whole page.

Create an XMLHttpRequest Object


All modern browsers (Chrome, IE7+, Firefox, Safari, and Opera) have a built-in XMLHttpRequest object.
Syntax for creating an XMLHttpRequest object:
variable = new XMLHttpRequest();
Old versions of Internet Explorer (IE5 and IE6) use an ActiveX Object:
variable = new ActiveXObject("Microsoft.XMLHTTP");
To handle all browsers, including IE5 and IE6, check if the browser supports the XMLHttpRequest object. If it does, create an
XMLHttpRequest object, if not, create an ActiveXObject:
Example
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
2

} else {
// code for IE6, IE5
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
Send a Request To a Server
To send a request to a server, we use the open() and send() methods of the XMLHttpRequest object:
xhttp.open("GET",
xhttp.send();
Method
open(method, url, async)
send()
send(string)

"ajax_info.txt",

Description
Specifies the type of request
method: the type of request: GET or POST
url: the server (file) location
async: true (asynchronous) or false (synchronous)
Sends the request to the server (used for GET)
Sends the request to the server (used for POST)

GET or POST?
GET is simpler and faster than POST, and can be used in most cases.
However, always use POST requests when:

A cached file is not an option (update a file or database on the server).

Sending a large amount of data to the server (POST has no size limitations).

Sending user input (which can contain unknown characters), POST is more robust and secure than GET.

GET Requests
A simple GET request:
Example
xhttp.open("GET", "demo_get.asp", true);
xhttp.send();
In the example above, you may get a cached result. To avoid this, add a unique ID to the URL:
Example
xhttp.open("GET", "demo_get.asp?t=" + Math.random(), true);
xhttp.send();
If you want to send information with the GET method, add the information to the URL:

true);

Example
xhttp.open("GET", "demo_get2.asp?fname=Henry&lname=Ford", true);
xhttp.send();

POST Requests
A simple POST request:
Example
xhttp.open("POST", "demo_post.asp", true);
xhttp.send();
To POST data like an HTML form, add an HTTP header with setRequestHeader(). Specify the data you want to send in the
send() method:
Example
xhttp.open("POST", "ajax_test.asp", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("fname=Henry&lname=Ford");

Method

Description
Adds HTTP headers to the request

setRequestHeader(header
, value)
header: specifies the header name
value: specifies the header value
The url - A File On a Server
The url parameter of the open() method, is an address to a file on a server:
xhttp.open("GET", "ajax_test.asp", true);
The file can be any kind of file, like .txt and .xml, or server scripting files like .asp and .php (which can perform actions on the
server before sending the response back).

Asynchronous - True or False?


AJAX stands for Asynchronous JavaScript and XML, and for the XMLHttpRequest object to behave as AJAX, the async
parameter of the open() method has to be set to true:
xhttp.open("GET", "ajax_test.asp", true);
Sending asynchronous requests is a huge improvement for web developers. Many of the tasks performed on the server are
very time consuming. Before AJAX, this operation could cause the application to hang or stop.
With AJAX, the JavaScript does not have to wait for the server response, but can instead:
4

execute other scripts while waiting for server response

deal with the response when the response ready

Async=true
When using async=true, specify a function to execute when the response is ready in the onreadystatechange event:
Example
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
You will learn more about onreadystatechange in a later chapter.

Async=false
To use async=false, change the third parameter in the open() method to false:
xhttp.open("GET", "ajax_info.txt", false);
Using async=false is not recommended, but for a few small requests this can be ok.
Remember that the JavaScript will NOT continue to execute, until the server response is ready. If the server is busy or slow, the
application will hang or stop.
Note: When you use async=false, do NOT write an onreadystatechange function - just put the code after the send() statement:
Example
xhttp.open("GET", "ajax_info.txt", false);
xhttp.send();
document.getElementById("demo").innerHTML = xhttp.responseText;

5.3 CALL BACK METHODS


The ajaxSuccess( callback ) method attaches a function to be executed whenever an AJAX request completes successfully.
This is an Ajax Event.
Syntax
Here is the simple syntax to use this method
$(document).ajaxSuccess( callback )
5

Parameters
Here is the description of all the parameters used by this method

callback The function to execute. The event object, XMLHttpRequest, and settings used for that request are passed
as arguments to the callback.

Example
Assuming we have following HTML content in result.html file
<h1>THIS IS RESULT...</h1>
Following is a simple example a simple showing the usage of this method.
<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript"
src = "http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
/* Global variable */
var count = 0;
$("#driver").click(function(event){
$('#stage0').load('result.html');
});
/* Gets called when request starts */
$(document).ajaxStart(function(){
count++;
$("#stage1").html("<h1>Starts, Count :" + count + "</h1>");
});
/* Gets called when request is sent */
$(document).ajaxSend(function(evt, req, set){
count++;
$("#stage2").html("<h1>Sends, Count :" + count + "</h1>");
$("#stage2").append("<h1>URL :" + set.url + "</h1>");
});
/* Gets called when request completes */
$(document).ajaxComplete(function(event,request,settings){
count++;
$("#stage3").html("<h1>Completes,Count:" + count + "</h1>");
});
/* Gets called when request is stopped */
$(document).ajaxStop(function(event,request,settings){
count++;
$("#stage4").html("<h1>Stops, Count :" + count + "</h1>");
6

});
/* Gets called when all request completes successfully */
$(document).ajaxSuccess(function(event,request,settings){
count++;
$("#stage5").html("<h1>Success,Count :" + count + "</h1>");
});
});
</script>
</head>
<body>
<p>Click on the button to load result.html file:</p>
<div id = "stage0" style = "background-color:blue;">
STAGE - 0
</div>
<div id = "stage1" style = "background-color:blue;">
STAGE - 1
</div>
<div id = "stage2" style = "background-color:blue;">
STAGE - 2
</div>
<div id = "stage3" style = "background-color:blue;">
STAGE - 3
</div>
<div id = "stage4" style = "background-color:blue;">
STAGE - 4
</div>
<div id = "stage5" style = "background-color:blue;">
STAGE - 5
</div>
<input type = "button" id = "driver" value="Load Data" />
</body>
</html>
AJAX is an acronym standing for Asynchronous JavaScript and XML and this technology help us to load data from the server
without a browser page refresh.
If you are new with AJAX, I would recommend you go through our Ajax Tutorial before proceeding further.
JQuery is a great tool which provides a rich set of AJAX methods to develop next generation web application.
Loading simple data
This is very easy to load any static or dynamic data using JQuery AJAX. JQuery provides load() method to do the job
7

Syntax
Here is the simple syntax for load() method
[selector].load( URL, [data], [callback] );
Here is the description of all the parameters

URL The URL of the server-side resource to which the request is sent. It could be a CGI, ASP, JSP, or PHP script
which generates data dynamically or out of a database.

data This optional parameter represents an object whose properties are serialized into properly encoded parameters
to be passed to the request. If specified, the request is made using the POST method. If omitted, the GET method is
used.

callback A callback function invoked after the response data has been loaded into the elements of the matched set.
The first parameter passed to this function is the response text received from the server and second parameter is the
status code.

Example
Consider the following HTML file with a small JQuery coding
<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript"
src = "http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("#driver").click(function(event){
$('#stage').load('/jquery/result.html');
});
});
</script>
</head>
<body>
<p>Click on the button to load /jquery/result.html file </p>
<div id = "stage" style = "background-color:cc0;">
STAGE
</div>
<input type = "button" id = "driver" value = "Load Data" />
</body>
</html>
Here load() initiates an Ajax request to the specified URL /jquery/result.html file. After loading this file, all the content would be
populated inside <div> tagged with ID stage. Assuming, our /jquery/result.html file has just one HTML line
<h1>THIS IS RESULT...</h1>
8

When you click the given button, then result.html file gets loaded.
Getting JSON data
There would be a situation when server would return JSON string against your request. JQuery utility function getJSON()
parses the returned JSON string and makes the resulting string available to the callback function as first parameter to take
further action.
Syntax
Here is the simple syntax for getJSON() method
[selector].getJSON( URL, [data], [callback] );
Here is the description of all the parameters

URL The URL of the server-side resource contacted via the GET method.

data An object whose properties serve as the name/value pairs used to construct a query string to be appended to
the URL, or a preformatted and encoded query string.

callback A function invoked when the request completes. The data value resulting from digesting the response body
as a JSON string is passed as the first parameter to this callback, and the status as the second.

Example
Consider the following HTML file with a small JQuery coding
<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript"
src = "http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("#driver").click(function(event){
$.getJSON('/jquery/result.json', function(jd) {
$('#stage').html('<p> Name: ' + jd.name + '</p>');
$('#stage').append('<p>Age : ' + jd.age+ '</p>');
$('#stage').append('<p> Sex: ' + jd.sex+ '</p>');
});
});
});
</script>
</head>
<body>
<p>Click on the button to load result.json file </p>
<div id = "stage" style = "background-color:#eee;">
STAGE
9

</div>
<input type = "button" id = "driver" value = "Load Data" />
</body>
</html>
Here JQuery utility method getJSON() initiates an Ajax request to the specified URL result.json file. After loading this file, all
the content would be passed to the callback function which finally would be populated inside <div> tagged with ID stage.
Assuming, our result.json file has following json formatted content
{
"name": "Zara Ali",
"age" : "67",
"sex": "female"
}
When you click the given button, then result.json file gets loaded.
Passing data to the Server
Many times you collect input from the user and you pass that input to the server for further processing. JQuery AJAX made it
easy enough to pass collected data to the server using data parameter of any available Ajax method.
Example
This example demonstrate how can pass user input to a web server script which would send the same result back and we
would print it
<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript"
src = "http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("#driver").click(function(event){
var name = $("#name").val();
$("#stage").load('/jquery/result.php', {"name":name} );
});
});
</script>
</head>
<body>
<p>Enter your name and click on the button:</p>
<input type = "input" id = "name" size = "40" /><br />
<div id = "stage" style = "background-color:cc0;">
STAGE
</div>
<input type = "button" id = "driver" value = "Show Result" />

10

</body>
</html>
Here is the code written in result.php script
<?php
if( $_REQUEST["name"] ){
$name = $_REQUEST['name'];
echo "Welcome ". $name;
}
?>
Now you can enter any text in the given input box and then click "Show Result" button to see what you have entered in the
input box.
JQuery AJAX Methods
You have seen basic concept of AJAX using JQuery. Following table lists down all important JQuery AJAX methods which you
can use based your programming need
S.N
Methods & Description
.
jQuery.ajax( options )
1
Load a remote page using an HTTP request.
jQuery.ajaxSetup( options )
2
Setup global settings for AJAX requests.
jQuery.get( url, [data], [callback], [type] )
3
Load a remote page using an HTTP GET request.
jQuery.getJSON( url, [data], [callback] )
4
Load JSON data using an HTTP GET request.
jQuery.getScript( url, [callback] )
5
Loads and executes a JavaScript file using an HTTP GET request.
jQuery.post( url, [data], [callback], [type] )
6
Load a remote page using an HTTP POST request.
load( url, [data], [callback] )
7
Load HTML from a remote file and inject it into the DOM.
serialize( )
8
Serializes a set of input elements into a string of data.
serializeArray( )
9 Serializes all forms and form elements like the .serialize() method but returns a JSON
data structure for you to work with.
JQuery AJAX Events
You can call various JQuery methods during the life cycle of AJAX call progress. Based on different events/stages following
methods are available
You can go through all the AJAX Events.
S.N. Methods & Description
ajaxComplete( callback )
1
Attach a function to be executed whenever an AJAX request completes.
2
ajaxStart( callback )
11

Attach a function to be executed whenever an AJAX request begins and there is none already active.
ajaxError( callback )
Attach a function to be executed whenever an AJAX request fails.
ajaxSend( callback )
Attach a function to be executed before an AJAX request is sent.
ajaxStop( callback )
Attach a function to be executed whenever all AJAX requests have ended.
ajaxSuccess( callback )
Attach a function to be executed whenever an AJAX request completes successfully.

3
4
5
6

5.4 WEB SERVICES: INTRODUCTIONWeb services are open standard (XML, SOAP, HTTP etc.) based Web applications that interact with other web applications for
the purpose of exchanging data.
Web Services can convert your existing applications into Web-applications.
Different books and different organizations provide different definitions to Web Services. Some of them are listed here.

A 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. As 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, 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.

To summarize, a complete web service is, therefore, any service that:

Is available over the Internet or private (intranet) networks

Uses a standardized XML messaging system

Is not tied to any one operating system or programming language

Is self-describing via a common XML grammar

Is discoverable via a simple find mechanism


12

Components of Web Services


The basic web services platform is XML + HTTP. All the standard web services work using the following components

SOAP (Simple Object Access Protocol)

UDDI (Universal Description, Discovery and Integration)

WSDL (Web Services Description Language)

All these components have been discussed in the Web Services Architecture chapter.
How Does a Web Service Work?
A web service enables communication among various applications by using open standards such as HTML, XML, WSDL, and
SOAP. A web service takes the help of:

XML to tag the data

SOAP to transfer a message

WSDL to describe the availability of service.

You can build a Java-based web service on Solaris that is accessible from your Visual Basic program that runs on Windows.
You 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.

Example
Consider a simple account-management and order processing system. The accounting personnel use a client application built
with Visual Basic or JSP to create new accounts and enter new customer orders.
The processing logic for this system is written in Java and resides on a Solaris machine, which also interacts with a database to
store information.
The steps to perform this operation are as follows:

The client program bundles the account registration information into a SOAP message.

13

This SOAP message is sent to the web service as the body of an HTTP POST request.

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.

Next, the web service packages the response into another SOAP message, which it sends back to the client program
in response to its HTTP request.

The client program unpacks the SOAP message to obtain the results of the account registration process.

Types of Web Services


There are mainly two types of web services.
1. SOAP web services.
2. RESTful web services.

5.5 JAVA WEB SERVICES BASICS


Java web services tutorial provides concepts and examples of two main java web services api: JAX-WS and JAX-RS. The
java web service application can be accessed by other programming languages such as .Net and PHP.
Java web service application perform communication through WSDL (Web Services Description Language). There are two
ways to write java web service application code: SOAP and RESTful.

Java Web Services API


There are two main API's defined by Java for developing web service applications since JavaEE 6.
1) JAX-WS: for SOAP web services. The are two ways to write JAX-WS application code: by RPC style and Document style.
2) JAX-RS: for RESTful web services. There are mainly 2 implementation currently in use for creating JAX-RS application:
Jersey and RESTeasy.

14

5.6 CREATING, PUBLISHING, TESTING AND DESCRIBING A WEB SERVICES (WSDL)


WSDL stands for Web Services Description Language. It is the standard format for describing a web service. WSDL was
developed jointly by Microsoft and IBM.
Features of WSDL

WSDL is an XML-based protocol for information exchange in decentralized and distributed environments.

WSDL definitions describe how to access a web service and what operations it will perform.

WSDL is a language for describing how to interface with XML-based services.

WSDL is an integral part of Universal Description, Discovery, and Integration (UDDI), an XML-based worldwide
business registry.

WSDL is the language that UDDI uses.

15

WSDL is pronounced as 'wiz-dull' and spelled out as 'W-S-D-L'.

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.
History of WSDL
WSDL 1.1 was submitted as a W3C Note by Ariba, IBM, and Microsoft for describing services for the W3C XML Activity on XML
Protocols in March 2001.
WSDL 1.1 has not been endorsed by the World Wide Web Consortium (W3C), however it has just released a draft for version
2.0 that will be a recommendation (an official standard), and thus endorsed by the W3C.
WSDL breaks down web services into three specific, identifiable elements that can be combined or reused once defined.
The three major elements of WSDL that can be defined separately are:

Types

Operations

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.
WSDL Elements
A WSDL document contains the following elements:

Definition : It is 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 to be used in the messages are in the form of XML schemas.

Message : It is 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 : It is 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 : It is an abstract set of operations mapped to one or more end-points, defining the collection of operations
for a binding; the collection of operations, as it is abstract, can be mapped to multiple transports through various
bindings.

Binding : It is the concrete protocol and data formats for the operations and messages defined for a particular port
type.

16

Port : It is a combination of a binding and a network address, providing the target address of the service
communication.

Service : It is 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:

Documentation: This element is used to provide human-readable documentation and can be included inside any
other WSDL element.

Import : This element is used to import other WSDL documents or XML Schemas.

NOTE: WSDL parts are usually generated automatically using web services-aware tools.
The WSDL Document Structure
The main structure of a WSDL document looks like this:
<definitions>
<types>
definition of types........
</types>
<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.
Proceed further to analyze an example of WSDL Document.
WSDL - <definition> Element
he <definitions> element must be the root element of all WSDL documents. It defines the name of the web service.
Here is the piece of code from the last chapter that uses the definitions element.

17

<definitions name="HelloService"
targetNamespace="http://www.examples.com/wsdl/HelloService.wsdl"
xmlns="http://schemas.xmlsoap.org/wsdl/"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:tns="http://www.examples.com/wsdl/HelloService.wsdl"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
................................................
</definitions>
From the above example, we can conclude that definitions:

is a container of all the other elements.

specifies that this document is called HelloService.

specifies a targetNamespace attribute. The targetNamespace is a convention of XML Schema that enables the WSDL
document to refer to itself. In this example, we have specified a targetNamespace of
http://www.examples.com/wsdl/HelloService.wsdl

specifies a default namespace: xmlns=http://schemas.xmlsoap.org/wsdl/. All elements without a namespace prefix,


such as message or portType, are therefore assumed to be a part of the default WSDL namespace.

specifies numerous namespaces that are used throughout the remainder of the document.

5.7 CONSUMING A WEB SERVICE


Creating and Publishing Web Service

18

1. Create a Java Project CalcWS.

2. Create a package com.theopentutorials.ws.calc.

19

3. Create a Java class Calculator and type the following code.

01
02
03
04
05
06
07
08
09
10
11
12
13
14

package com.theopentutorials.ws.calc;
import javax.jws.WebService;
@WebService
public class Calculator {
public int add(int a, int b) {
return (a + b);
}
public int sub(int a, int b) {
return (a - b);
}
}

4. @WebService annotation at the beginning of the class definition tells the Java interpreter that we intend to publish ALL
the methods of this class as a web service. If we want to publish only particular methods then we can use
@WebMethod annotation before the method signature.

20

5. In order to publish our class and its methods as web service we need to crate appropriate stub files or artifacts for web
service deployment and invocation. Fortunately Java provides a tool called wsgen which generates JAX-WS portable
artifacts used in JAX-WS web services.
6. Open command prompt or terminal in Linux and go to the project folder CalcWS.
7. Now issue the following command,
wsgen -cp bin -d bin com.theopentutorials.ws.calc.Calculator
the cp option specifies the classpath for our Calculator class which is in bin folder, the d option specifies where to
place generated output files which is also the bin folder in our case.

8. We can also have a look at the source of the generated files by using the s option provided by wsgen.
wsgen -s src -cp bin -d bin com.theopentutorials.ws.calc.Calculator

21

9. Now we need to publish our class as a web service endpoint. For that we use the static publish() method of the
javax.xml.ws.Endpoint class to publish our Calculator class as a web service in the specified context root.

22

10. Create a package com.theopentutorials.ws.calc.endpoint.

11. Create a class CalcEndpointPublisher with main method and type the following code.

23

01
02
03
04
05
06
07
08
09
10
11
12
13

package com.theopentutorials.ws.calc.endpoint;
import javax.xml.ws.Endpoint;
import com.theopentutorials.ws.calc.Calculator;
public class CalcEndpointPublisher {
public static void main(String[] args) {
Endpoint.publish("http://localhost:8080/CalcWS/Calculator",
new Calculator());
}
}

12. Run this class as Java Application.


13. You may not get output in the Console. To check whether our class is published as web service, open a browser and
type the URL mentioned in the endpoint with a parameter ?wsdl appended.
http://localhost:8080/CalcWS/Calculator?wsdl
14. When you run the application, the Java SE 6 platform has a small web application server that will publish the web
service at the address http://localhost:8080/CalcWS/Calculator while the JVM is running.
15. If you see a large amount of XML that describes the functionality behind the web service, then the deployment is
successful.

Creating and consuming a Web Service Client


1. Having published the web service, we now create a client which communicates with the service and displays the
result.

24

2. Create a Java project CalcWSClient.

3. Just like wsgen, JAX-WS also provides a tool called wsimport for generating the artifacts required for creating and
consuming a web service. wsimport takes a wsdl file as input.
4. From the project folder in command prompt or terminal, issue the following command,
wsimport -s src -d bin http://localhost:8080/CalcWS/Calculator?wsdl

25

5. This will generate many files as shown in the below file hierarchy tree.

6. Let us now create a Java class with main method to run this client. Create a package
com.theopentutorials.ws.calc.client

26

7. In that package, create a class CalcClient with main method and type the following code.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16

package com.theopentutorials.ws.calc.client;
import com.theopentutorials.ws.calc.Calculator;
import com.theopentutorials.ws.calc.CalculatorService;
public class CalcClient {
public static void main(String[] args) {
int a = 10;
int b = 12;
CalculatorService calcService = new CalculatorService();
Calculator calc = calcService.getCalculatorPort();
System.out.println(a + " + " + b + " = " + calc.add(a, b));
System.out.println(a + " - " + b + " = " + calc.sub(a, b));
}
}

8. Run this class as Java Application.


9. You will get the following output in the console.
10 + 12 = 22
10 12 = -2
5.8 DATABASE DRIVEN WEB SERVICE FROM AN APPLICATION
he user registration/account registration form will be presented to the user. Once user fills in the form and clicks on the "OK"
button, the serverside JSP will call the webservice to register the user.
This webservices will expose the insert user operation which will be used by the JSP client to register the user. We will use the
27

NetBeans 6.1 IDE to develop and test the application.


The MySQL database is used to save the user registration data. You can modify the code to use any database of your choice.
The existing webservices can also be modified to use the Hibernate or any other ORM technologies. You can also use the
Entity beans to persist the data into database.
Software required to develop and run this example:

JDK 1.6

NetBeans 6.1

MySQL Database 5 or above

Let's get started with the development of the applicaton


MySql Database Configuration In NetBeans
Let's configure MySQL database in teh 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.

Fig.
Step 2:

Right Click on the Databases

Select New Connection as shown below in Fig 2.

28

Fig. 2.
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.

Fig. 3
Step 4:

Click on the Ok button .

Now expand the Newly created database connection.

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

29

Fig. 4
Step 5:

Create a table named login.

Right Click on the Tables and select Create table


as shown below in Fig 5

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.

30

Fig. 6
Step 7:

Click on the Ok

It creates the table login in the test database.


Creating the WebService program for Account creation
Step 8:

Open the netbeans 6.1

Creat a new web project as shown below in Fig 7.

Fig. 7
Step 9:

Type the project Name as MyAccount

Click on the next button as shown below in Fig 8.

31

Fig. 8
Step 10:

Select the server as Glassfish

Click on the Next and then finish button as shown below in Fig 9.

Fig. 9
Step 11:

It creates a Web Project named MyAccount.


Creating the WebService
Step 12:

Right Click on the project MyAccount

Select New-->WebService as shown below in Fig 10.

32

Fig. 10
Step 13:

Type the name of the WebService as myaccount with the package as mypack.

Click on the Finish button as shown below in Fig 11.

Fig. 11
Step 14:

It creates a WebService application in design view

Click on the Add operation as shown below in Fig 12.

33

Fig. 12
Step 15:

In the dialog box type all parameter names.

Also select the appropriate data type.

Click on Ok as shown below in Fig 13.

Fig. 13
Step 16:

It creates a WebService application

Click on the source tab as shown below in the Fig 14.

34

Fig. 14
Step 17:

Now create the database source

Right Click in the source code of myaccount.java

Select the Enterprise Resources-->Use Database as shown below in Fig 15.

35

Fig. 15
Step 18:

In the choose database select the Add button as shown below in Fig 16.

Fig. 16
Step 19:

It opens a Add Data Source Reference.

Type the Reference Name as data1

For Project Data Sources Click on the Add button as shown below in Fig 17.

Fig. 17
Step 20:

In the Crea Data Source type thye jndi name as jndi1

In the database connection select the newly created database connction for the mysql.
as shown below in Fig 18.

36

Fig. 18
Step 21:

Click on the Ok button

It creates the database connection gives the dialog box as shown below.

Click on the Ok button as shown below in Fig 19.

Fig. 19

5.9 SOAP
SOAP is an open-standard, XML-based messaging protocol for exchanging information among computers. This is a
brief tutorial that introduces the readers to the fundamentals of SOAP before moving on to explain its various elements,
encoding, and how SOAP is transported.
SOAP is an acronym for Simple Object Access Protocol. It is an XML-based messaging protocol for exchanging information
among computers. SOAP is an application of the XML specification.
Points to Note
Below mentioned are some important point which the user should take note of. These points briefly describes the nature of
SOAP

SOAP is a communication protocol designed to communicate via Internet.

37

SOAP can extend HTTP for XML messaging.

SOAP provides data transport for Web services.

SOAP can exchange complete documents or call a remote procedure.

SOAP can be used for broadcasting a message.

SOAP is platform- and language-independent.

SOAP is the XML way of defining what information is sent and how.

SOAP enables client applications to easily connect to remote services and invoke remote methods.

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.
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.
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.

All these elements are declared in the default namespace for the SOAP envelope
http://www.w3.org/2001/12/soap-envelope and the default namespace for SOAP encoding and data types is
http://www.w3.org/2001/12/soap-encoding
NOTE All these specifications are subject to change. So keep updating yourself with the latest specifications available on the
W3 website.
SOAP Message Structure
The following block depicts the general structure of a SOAP message
<?xml version="1.0"?>
<SOAP-ENV:Envelope
xmlns:SOAP-ENV="http://www.w3.org/2001/12/soap-envelope"
ENV:encodingStyle="http://www.w3.org/2001/12/soap-encoding">
<SOAP-ENV:Header>
...
...
</SOAP-ENV:Header>

38

SOAP-

<SOAP-ENV:Body>
...
...
<SOAP-ENV:Fault>
...
...
</SOAP-ENV:Fault>
...
</SOAP-ENV:Body>
</SOAP_ENV:Envelope>
SOAP with HTTP POST
The 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 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 website.
POST /OrderEntry HTTP/1.1
Host: www.tutorialspoint.com
Content-Type: application/soap; charset="utf-8"
Content-Length: nnnn
<?xml version="1.0"?>
<SOAP-ENV:Envelope
xmlns:SOAP-ENV="http://www.w3.org/2001/12/soap-envelope"
http://www.w3.org/2001/12/soap-encoding">
...
Message information goes here
...
</SOAP-ENV:Envelope>

39

SOAP-ENV:encodingStyle="

Você também pode gostar