<<

PERIPERIIT IT CS8651- PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

UNIT V INTRODUCTION TO AND WEB SERVICES

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

AJAX -Asynchronous JavaScript And XML. AJAX is not a new programming language, but a new way to use existing standards. 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.

AJAX is a technique for creating fast and dynamic web pages.Classic web pages, (which do not use AJAX) must reload the entire page if the content should change.

Examples of applications using AJAX: , Gmail, Youtube, and Facebook tabs. How AJAX Works AJAX Client Server Architecture

i)The XMLHttpRequest Object

The keystone of AJAX is the XMLHttpRequest object. All modern browsers support the XMLHttpRequest object (IE5 and IE6 use an ActiveXObject).

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.

[Department of CSE] 1

PERIPERIIT IT CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

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 modern 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: ii) Send a Request To a Server

The XMLHttpRequest object is used to exchange data with a server.

To send a request to a server, we use the open() and send() methods of the XMLHttpRequest object: xmlhttp.open("GET","ajax_info.txt",true); xmlhttp.send();

Method Description

Specifies the type of request, the URL, and if the request should be handled asynchronously or not. open(method,url,async) method: the type of request: GET or POST url: the location of the file on the server async: true (asynchronous) or false (synchronous)

Sends the request off to the server. send(string) string: Only used for POST requests iii)The url - A File On a Server

The url parameter of the open() method, is an address to a file on a server: xmlhttp.open("GET","ajax_test.asp",true);

The file can be any kind of file, like .txt and ., or server scripting files like .asp and . (which can perform actions on the server before sending the response back). iv)Asynchronous - True or False?

[Department of CSE] 2

PERIPERIIT IT CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

a)Async=true

When using async=true, specify a function to execute when the response is ready in the onreadystatechange event:

Example: xmlhttp.open("GET","ajax_info.txt",true); b)Async=false

To use async=false, change the third parameter in the open() method to false: xmlhttp.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.

Example xmlhttp.open("GET","ajax_info.txt",false); xmlhttp.send(); document.getElementById("myDiv").innerHTML=xmlhttp.responseText; v)AJAX - Server Response Server Response

To get the response from a server, use the responseText or responseXML property of the XMLHttpRequest object.

Property Description responseText get the response data as a string responseXML get the response data as XML data

The responseText Property

If the response from the server is not XML, use the responseText property. The responseText property returns the response as a string, and you can use it accordingly: Example: document.getElementById("myDiv").innerHTML=xmlhttp.responseText; vi)AJAX - The onreadystatechange Event

[Department of CSE] 3

PERIPERIIT IT CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

The onreadystatechange event

 When a request to a server is sent, we want to perform some actions based on the response.  The onreadystatechange event is triggered every time the readyState changes.  The readyState property holds the status of the XMLHttpRequest.

Three important properties of the XMLHttpRequest object:

Property Description

Stores a function (or the name of a function) to be called automatically each onreadystatechange time the readyState property changes

Holds the status of the XMLHttpRequest. Changes from 0 to 4: 0: request not initialized 1: server connection established readyState 2: request received 3: processing request 4: request finished and response is ready

200: "OK" Status 404: Page not found

In the onreadystatechange event, we specify what will happen when the server response is ready to be processed.

When readyState is 4 and status is 200, the response is ready:

AJAX Example: To understand how AJAX works, we will create a small AJAX application:

Eg:

Let AJAX change this text

Input: info.txt AJAX is not a new programming language. AJAX is a technique for creating fast and dynamic web pages.

Output:  AJAX is not a new programming language.  AJAX is a technique for creating fast and dynamic web pages.

AJAX Example Explained

 The AJAX application above contains one div section and one button.  The div section will be used to display information returned from a server. The button calls a function named loadXMLDoc(), if it is clicked:

XMLHttpRequest Object

The XMLHttpRequest object is the key to AJAX. It has been available ever since Internet Explorer 5.5 was released in July 2000, but was not fully discovered until AJAX and Web 2.0 in 2005 became popular.

XMLHttpRequest (XHR) is an API that can be used by JavaScript, JScript, VBScript, and other web browser scripting languages to transfer and manipulate XML data to and from a webserver using HTTP, establishing an independent connection channel between a webpage's Client-Side and Server-Side.

[Department of CSE] 5

PERIPERIIT IT CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

The data returned from XMLHttpRequest calls will often be provided by back-end databases. Besides XML, XMLHttpRequest can be used to fetch data in other formats, e.g. JSON or even plain text. Listed below are some of the methods and properties that you have to get familiar with. XMLHttpRequest Methods  abort() o Cancels the current request.  getAllResponseHeaders() o Returns the complete set of HTTP headers as a string.  getResponseHeader( headerName ) o Returns the value of the specified HTTP header.  open( method, URL )  open( method, URL, async )  open( method, URL, async, userName )  open( method, URL, async, userName, password )

Specifies the method, URL, and other optional attributes of a request.The method parameter can have a value of "GET", "POST", or "HEAD". Other HTTP methods such as "PUT" and "DELETE" (primarily used in REST applications) may be possible.

The "async" parameter specifies whether the request should be handled asynchronously or not. "true" means that the script processing carries on after the send() method without waiting for a response, and "false" means that the script waits for a response before continuing script processing.

 send( content ) o Sends the request.  setRequestHeader( label, value ) o Adds a label/value pair to the HTTP header to be sent.

XMLHttpRequest Properties  onreadystatechange o An event handler for an event that fires at every state change.  readyState The readyState property defines the current state of the XMLHttpRequest object. The following table provides a list of the possible values for the readyState property ,

State Description 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 completed.

[Department of CSE] 6

PERIPERIIT IT CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE readyState = 0 After you have created the XMLHttpRequest object, but before you have called the open() method. readyState = 1 After you have called the open() method, but before you have called send(). readyState = 2 After you have called send(). readyState = 3 After the browser has established a communication with the server, but before the server has completed the response. readyState = 4 After the request has been completed, and the response data has been completely received from the server.  responseText Returns the response as a string.  responseXML Returns the response as XML. This property returns an XML document object, which can be examined and parsed using the W3C DOM node tree methods and properties.  status Returns the status as a number (e.g., 404 for "Not Found" and 200 for "OK").  statusText Returns the status as a string (e.g., "Not Found" or "OK"). Callback Methods

 A callback function is a function passed as a parameter to another function.  If you have more than one AJAX task on your website, you should create ONE standard function for creating the XMLHttpRequest object, and call this for each AJAX task.  The function call should contain the URL and what to do on onreadystatechange (which is probably different for each call)

Syntax: function myFunction() { loadXMLDoc("ajax_info.txt",function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } }); }

Eg:

Let AJAX change this text

info.txt

AJAX is not a new programming language. AJAX is a technique for creating fast and dynamic web pages.

Output:

AJAX is not a new programming language. AJAX is a technique for creating fast and dynamic web pages.

[Department of CSE] 8

PERIPERIIT IT CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

Web Services A Web service is a method of communication between two electronic devices over the web (internet).

The W3C defines a "Web service" as "a system designed to support interoperable machine-to-machine interaction over a network". It has an interface described in a machine- processable format (specifically Web Services Description Language, known by the acronym WSDL). Other systems interact with the Web service in a manner prescribed by its description using SOAP messages, typically conveyed using HTTP with an XML in conjunction with other Web-related standards."

 Web services are application components  Web services communicate using open protocols  Web services are self-contained and self-describing  Web services can be discovered using UDDI  Web services can be used by other applications  XML is the basis for Web services

Java Web Services

Java provides it’s own API to create both SOAP as well as REST web services.  JAX-WS: JAX-WS stands for Java API for XML Web Services. JAX-WS is XML based Java API to build web services server and client application.  JAX-RS: Java API for RESTful Web Services (JAX-RS) is the Java API for creating REST web services. JAX-RS uses annotations to simplify the development and deployment of web services.

Web services that use markup languages There are a number of Web services that use markup languages:  JSON-RPC.  JSON-WSP  Representational state transfer (REST) versus (RPC)  Web Services Conversation Language (WSCL)  Web Services Description Language (WSDL), developed by the W3C  Web Services Flow Language (WSFL), superseded by BPEL  Web template  WS-MetadataExchange

Why web service?  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.

[Department of CSE] 9

PERIPERIIT IT CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

 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.  Web services are XML-based information exchange systems that use the Internet for direct application-to-application interaction.  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

Web services platform elements:

 SOAP (Simple Object Access Protocol)  UDDI (Universal Description, Discovery and Integration)  WSDL (Web Services Description Language)

Web Services have Two Types of Uses

Reusable application-components: There are things applications need very often. So why make these over and over again? Web services can offer application-components like: currency conversion, weather reports, or even language translation as services. Connect existing software: Web services can help to solve the interoperability problem by giving different applications a way to link their data. With Web services you can exchange data between different applications and different platforms.

How Does a Web Service Work?

 The steps to perform this operation are as follows −  The client program bundles the account registration information into a SOAP message.  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.

Why Web Services? A few years ago Web services were not fast enough to be interesting.

Interoperability has Highest Priority

When all major platforms could access the Web using Web browsers, different platforms could interact. For these platforms to work together, Web-applications were developed. Web-

[Department of CSE] 10

PERIPERIIT IT CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE applications are simple applications that run on the web. These are built around the Web browser standards and can be used by any browser on any platform.Web Services take Web-applications to the Next Level By using Web services, your application can publish its function or message to the rest of the world.Web services use XML to code and to decode data, and SOAP to transport it (using open protocols).With Web services, your accounting department's Win 2k server's billing system can connect with your IT supplier's UNIX server.

Web Services - Characteristics

XML-Based

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

Coarse-Grained- Object-oriented technologies such as Java expose their services through individual methods.

Ability to be Synchronous or Asynchronous- Synchronicity refers to the binding of the client to the execution of the service.

Supports Remote Procedure Calls(RPCs)- Web services allow clients to invoke procedures, functions, and methods on remote objects using an XML-based protocol.

Supports Document Exchange- One of the key advantages of XML is its generic way of representing not only data, but also complex documents.

Web Service Roles

There are three major roles within the web service architecture −

 Service Provider  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 clearing house for companies and their services.

[Department of CSE] 11

PERIPERIIT IT CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

Web Services – Architecture

Web services architecture: the service provider sends a WSDL file to UDDI. The service requester contacts UDDI to find out who is the provider for the data it needs, and then it contacts the service provider using the SOAP protocol. The service provider validates the service request and sends structured data in an XML file, using the SOAP protocol. This XML file would be validated again by the service requester using an XSD file.

Web Service Protocol Stack

Service Transport- This layer is responsible for transporting messages between applications. Currently, this layer includes Hyper Text Transport Protocol (HTTP), Simple Mail Transfer Protocol (SMTP), (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).

[Department of CSE] 12

PERIPERIIT IT CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

Web Services – Components Three primary technologies have emerged as worldwide standards that make up the core of today's web services technology

XML-RPC  This is the simplest XML-based protocol for exchanging information between computers.  XML-RPC is a simple protocol that uses XML messages to perform RPCs.  Requests are encoded in XML and sent via HTTP POST.  XML responses are embedded in the body of the HTTP response.  XML-RPC is platform-independent.  XML-RPC allows diverse applications to communicate.  A Java client can speak XML-RPC to a Perl server.  XML-RPC is the easiest way to get started with web services SOAP  SOAP is an XML-based protocol for exchanging information between computers.  SOAP is a .  SOAP is for communication between applications.  SOAP is a format for sending messages.  SOAP is designed to communicate via Internet.  SOAP is platform independent.  SOAP is language independent.  SOAP is simple and extensible.  SOAP allows you to get around firewalls.  SOAP will be developed as a W3C standard.

WSDL  WSDL is an XML-based language for describing web services and how to access them.  WSDL stands for Web Services Description Language.  WSDL was developed jointly by Microsoft and IBM.  WSDL is an XML based protocol for information exchange in decentralized and distributed environments.  WSDL is the standard format for describing a web service.  WSDL definition describes 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 UDDI, an XML-based worldwide business registry.  WSDL is the language that UDDI uses.  WSDL is pronounced as 'wiz-dull' and spelled out as 'W-S-D-L'.

UDDI  UDDI is an XML-based standard for describing, publishing, and finding web services.  UDDI stands for Universal Description, Discovery, and Integration.  UDDI is a specification for a distributed registry of web services.

[Department of CSE] 13

PERIPERIIT IT CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

 UDDI is platform independent, open framework.  UDDI can communicate via SOAP, CORBA, and Java RMI Protocol.  UDDI uses WSDL to describe interfaces to web services.  UDDI is seen with SOAP and WSDL as one of the three foundation standards of web services.  UDDI is an open industry initiative enabling businesses to discover each other and define how they interact over the Internet.

Web Services : Web services are the software components which can be accessed remotely using method calls.They facilitate reusability and portability of software in application.They use XML and HTTP for interaction beyween other services.Many Java API’s supportbthe concept of web services.They can be published using some tools that implements them and invoke their methods on client applications.One such tools is “Netbeans” developed by “Sun”.

The process of providing a web service whenever there are client request is known as publishing a web service.

Creating a Web Service:

In Netbeans,the initial step to create a web service is to create a “ project”.The step to create a web application are as follows,

1.Initially select “New Project” from the file option.This opens “New Project” dialog box. 2.Select “Web” from the dialog box. 3.Select “Web Application” from the list of Project” and click “Next” 4.Name the Project(WebApplication1) and specify the location to store the project in “Project Name” and “Project Location” fileds respectively.This location can be specified using the “Browser “button. 5.Then select Glass Fish Server and Java EE5 from server and J2EE version from drop-down list. 6.Finally click on “Finish” button.

Now a web service class must be included to this web application project.The step to include a web service class are as follows,

1.Initially go to “Project” tab and right-click on the project “WebApplication1”. 2.Then select web service from the New option.This opens “NewWebService” dialog box. 3.Specify the name in web service name and package fields with suitable names. 4.Finally click on “Finish “ button.

[Department of CSE] 14

PERIPERIIT IT CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

This creates a web service class name as WepApplication1.It resides in the “Project “tab in the web service node.

Eg:Simple web service program that display String Message package ttyt; import javax.jws.WebService; import javax.jws.WebMethod; import javax.jws.WebParam;

@WebService(serviceName = "NewWebService") public class NewWebService { @WebMethod(operationName = "hello") public String hello(@WebParam(name = "name") String txt) { return "Hello " + txt + " !"; } }

Input Page:

[Department of CSE] 15

PERIPERIIT IT CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

Output Page:

Publishing the web service: Publishing is the next step that is to be followed soon after creating the web service.Netbeans performs the publishing by managing building and deploying process of the web service.It uses the “Project” tab for this purpose.Whenever this tab is right-clicked,a pop up menu will appear.This menushows options necessary for building and developing the project.Some options are as follows,

1.Build Project: This option builds the project and return the compilation errors. 2.Deploy Project This option deploy the project on the server. 3.Run Project: This option performs the execution of the web application.It even builds or deploy the project if it was not build of deployed earlier.

Testing the web service:

Testing is the next step that is to be followed after publishing the web service.For sun Java System Application,server testing can be performed by creating a web page.This server creates a web page dynamically for this purpose and also test the methods. [Department of CSE] 16

PERIPERIIT IT CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

The steps for testing the methods of web service are as follows,

1.Initially select the project name from the “project” tab 2.Then select the “properties” option. This will display the “project Properties” dialog box. 3.Click on the “Run” option from the categories. 4.Type the URL in the “Relative URL” field. 5.Finally click on “OK” on the button.

After specifying the relative URL,the project must be run.Then the tester web page is build and loaded on the web browser from where the methods are to be tested.

The web service can be accessed when the is in running state.If the application server is build by Netbeans then it gets closed automatically when the developer closes the Netbeans.

Describing the web service:

Describing a web service is the next step after testing it.The description includes methods,parameters and return values.JAX-WS uses WSDL for this purpose.The application server software(SJSAS)dynamically creates a WSDL for the webservice.

Then the WSDL can be parsed by the client tools for generating the proxy class.This class can be used by the client to access the web service.The description of the web service obtained by the client would be new and updated since the WSDL is dynamically created.The WSDL for description can be viewed by opening the WSDL file link in the tester web page.Alternatively ,it can also be viewed from the browser by entering the URL of the web service.

Consuming a web Service:

Consuming a web service refers to accessing web service from the client application.The client application and proxy class objects are two main parts of an application that consumes web service.The proxy class object is used to communicate with web service. While the client application invokes methods on proxy class object for consuming the web service.The proxy class object acts as a web service reference that must be included in the application for consuming web service.

In netbeans ,the addition of web service reference will enables the IDE to create and compile client artifacts.The client invokes methods on proxy class object.This object makes use of the artifacts to communicate with the web service.

[Department of CSE] 17

PERIPERIIT IT CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

Adding a web service Reference:

To add a web service reference to an application it must be ensured that the web service has been successfully deployed.Moreover the glass fish server must be in running state.Then a client java desktop application must be created.After this the web service reference must be added.The step to add web service reference are as follows.

1.Initially right click on project name under “Project” tab. 2.Then new web service client must be created by selecting “web service client” from “new” option.This will display new web service client dialog box. 3.Specify the URL for WSDL in WSDL URL field.This URL states that the IDE must search for the WSDL description in specified address(URL). 4.Specify the package name in the “Package “ field. 5.Click on “finish “ button.

The specified WSDL description is used by IDE to create client artifacts tat produces and support the proxy.The new web service client dialog box allows the developers to search the web service in various locations.After specifying the web service that is to be consumed,its details can be viewed from a file.to Netbeans,copy the details and also save it in a file of the project.

Consuming the web service from web service Client:

Consuming the web service involves the interaction of a GUI application with the web service i.e Webapplication1 web service.For this ,a GUI for the client application must be build by including a subclass of .jsp page to the Project.The steps to be include the subclass are as follows,

1.Initially right-click on the project and select the JSP page. 2.create a JSP File name and press next and finish button. 3.Now open the JSp code and call the webService methods that you want . 4.The code to call the web service method has been created automatically and modify input alues. 5.Now Right click the web service Client application and press build,deploy. 6.Once deployed ,now right click on jsp page and press run button. 7. Web service get executed and output is displayed.

Eg: package ttyt; import javax.jws.WebService; import javax.jws.WebMethod; import javax.jws.WebParam; @WebService(serviceName = "NewWebService") public class NewWebService {

[Department of CSE] 18

PERIPERIIT IT CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

@WebMethod(operationName = "hello") public String hello(@WebParam(name = "name") String txt) { return "Hello " + txt + " !"; } }

WSDL URL: http://localhost:8080/WebApplication5/NewWebService?WSDL

On Web Service Client:

Myjsp.jsp

<%-- Document : myjsp Created on : Mar 7, 2020, 10:53:33 AM Author : R --%> <%@page contentType="text/html" pageEncoding="UTF-8"%> JSP Page

Hello World!

<%-- start web service invocation --%>
<% try { testh.NewWebService_Service service = new testh.NewWebService_Service(); testh.NewWebService port = service.getNewWebServicePort(); // TODO initialize WS operation arguments here java.lang.String name = "HELLO KUMAR"; // TODO process result here java.lang.String result = port.hello(name); out.println("Result = "+result); } catch (Exception ex) { // TODO handle custom exceptions here }

[Department of CSE] 19

PERIPERIIT IT CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

%> <%-- end web service invocation --%>


Output:

Result = Hello !

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.

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

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:

1. Types 2. Operations 3. Binding

[Department of CSE] 20

PERIPERIIT IT CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

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

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.

The WSDL Document Structure The main structure of a WSDL document looks like this:

definition of types...... definition of a message.... definition of a operation...... [Department of CSE] 21

PERIPERIIT IT CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

definition of a binding.... definition of a service....

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. Given below is a WSDL file that is provided to demonstrate a simple WSDL program.

Let us assume the service provides a single publicly available function, called sayHello. This function expects a single string parameter and returns a single string greeting. For example, if you pass the parameterworld then service function sayHello returns the greeting, "Hello, world!".

Example Contents of HelloService.wsdl file:

[Department of CSE] 22

PERIPERIIT IT CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

WSDL File for HelloService [Department of CSE] 23

PERIPERIIT IT CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

Example Analysis  Definitions : HelloServiceType : Using built-in data types and they are defined in XMLSchema.

 Message :

o sayHelloRequest : firstName parameter o sayHelloresponse: greeting return value  Port Type : sayHello operation that consists of a request and a response service.

 Binding : Direction to use the SOAP HTTP transport protocol.

 Service : Service available at http://www.examples.com/SayHello/

 Port : Associates the binding with the URI http://www.examples.com/SayHello/ where the running service can be accessed.

WSDL Ports

The element is the most important WSDL element.

It describes a web service, the operations that can be performed, and the messages that are involved.

The element can be compared to a function library (or a module, or a class) in a traditional programming language.

WSDL Messages

The element defines the data elements of an operation.

Each message can consist of one or more parts. The parts can be compared to the parameters of a function call in a traditional programming language.

WSDL Types

The element defines the data types that are used by the web service.

For maximum platform neutrality, WSDL uses XML Schema syntax to define data types.

[Department of CSE] 24

PERIPERIIT IT CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

WSDL Bindings

The element defines the data format and protocol for each port type.

WSDL Example

This is a simplified fraction of a WSDL document:

In this example the element defines "glossaryTerms" as the name of a port, and "getTerm" as the name of an operation.

The "getTerm" operation has an input message called "getTermRequest" and an output message called "getTermResponse".

The elements define the parts of each message and the associated data types.

Compared to traditional programming, glossaryTerms is a function library, "getTerm" is a function with "getTermRequest" as the input parameter, and getTermResponse as the return parameter.

WSDL PortType

The element is the most important WSDL element.

WSDL - The Element

The element defines a web service, the operations that can be performed, and the messages that are involved.

[Department of CSE] 25

PERIPERIIT IT CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

defines the connection point to a web service. It can be compared to a function library (or a module, or a class) in a traditional programming language. Each operation can be compared to a function in a traditional programming language.

Operation Types

The request-response type is the most common operation type, but WSDL defines four types:

Type Definition

One-way The operation can receive a message but will not return a response

Request-response The operation can receive a request and will return a response

Solicit-response The operation can send a request and will wait for a response

Notification The operation can send a message but will not wait for a response

One-Way Operation

A one-way operation example:

In the example above, the portType "glossaryTerms" defines a one-way operation called "setTerm".

The "setTerm" operation allows input of new glossary terms messages using a "newTermValues" message with the input parameters "term" and "value". However, no output is defined for the operation.

Request-Response Operation

A request-response operation example:

[Department of CSE] 26

PERIPERIIT IT CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

In the example above, the portType "glossaryTerms" defines a request-response operation called "getTerm".

The "getTerm" operation requires an input message called "getTermRequest" with a parameter called "term", and will return an output message called "getTermResponse" with a parameter called "value".

WSDL Bindings

WSDL bindings defines the message format and protocol details for a web service.

Binding to SOAP

A request-response operation example:

[Department of CSE] 27

PERIPERIIT IT CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

The binding element has two attributes - name and type.

The name attribute (you can use any name you want) defines the name of the binding, and the type attribute points to the port for the binding, in this case the "glossaryTerms" port.

The soap:binding element has two attributes - style and transport.

The style attribute can be "rpc" or "document". In this case we use document. The transport attribute defines the SOAP protocol to use. In this case we use HTTP.

The operation element defines each operation that the portType exposes.

For each operation the corresponding SOAP action has to be defined. You must also specify how the input and output are encoded. In this case we use "literal". Database Driven web service from an Application

Web service in general are accessed from desktop applications and can be used in web applications that are developed in Netbeans.The increasing use of web applications in business is enabling the use of web services to a great extent.The process of consuming a database-driven web service from a web application can be described by taking the example of a web service and its operation.

Eg:

Index.html JSP Page

From
To

[Department of CSE] 28

PERIPERIIT IT CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

Action.jsp:

<%@page contentType="text/html" pageEncoding="UTF-8"%> JSP Page

<%-- start web service invocation --%>


<% String f=request.getParameter("from"); String t=request.getParameter("to");

try { tt.NewWebService_Service service = new tt.NewWebService_Service(); tt.NewWebService port = service.getNewWebServicePort(); // TODO initialize WS operation arguments here java.lang.String from = f; java.lang.String to = t; // TODO process result here java.util.List result = port.get(from, to); out.println("Result = "+result); } catch (Exception ex) { // TODO handle custom exceptions here } %> <%-- end web service invocation --%>


NewWebService.java import javax.jws.WebService; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebParam; import java.sql.*;

[Department of CSE] 29

PERIPERIIT IT CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

/** * * @author 21csl130 */ @WebService(serviceName = "NewWebService") public class NewWebService { /** This is a sample web service operation */ /** * Web service operation */ @WebMethod(operationName = "get") public String[] get(@WebParam(name="from")String from,@WebParam (name="to")String to) { String hello[]=new String[6]; int i=0; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); String filename = "Z:/Database1.mdb"; String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ="; database+= filename.trim() + ";DriverID=22;READONLY=true}"; Connection con = DriverManager.getConnection( database ,"",""); Statement s = con.createStatement(); s.execute("select * from details where from='"+from+"' && to='"+to+"'"); ResultSet rs = s.getResultSet(); if (rs != null) while ( rs.next() ) { hello[i]= rs.getString("name"); i++; hello[i]= rs.getString("date"); i++; } } catch (Exception e) { System.out.println("Error: " + e); } return hello; } }

OUTPUT: i) Details table design:

[Department of CSE] 30

PERIPERIIT IT CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

Index.html

[Department of CSE] 31

PERIPERIIT IT CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

Result page:

NOTE:

Creating,publishing,describing ,deploying ,consuming a web service etc.., Create Web Service program Create WebSevice Client Program

REFER: lab program 11

Eg 2:Database driven web application using mySQL

Refer: http://www.roseindia.net/webservices/web-services-database.shtml

WebServices Example:

User Registration

We will develop a simple user registration Webservices. The 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

[Department of CSE] 32

PERIPERIIT IT CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE register the user. We will use the 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 Step 2:  Right Click on the Databases  Select New Connection Step 3:  It opens a dialog box for the mysql configuration.  Type the driver name, url , user name and password Step 4:  Click on the Ok button .  Now expand the Newly created database connection.  It shows the all the tables of the database test. Step 5:  Create a table named login.  Right Click on the Tables and select Create table Step 6:  It opens a dialog box for giving the fields name of the table..  Now give the field name and data type. Step 7:  Click on the Ok..  It creates the table login in the test database.

[Department of CSE] 33

PERIPERIIT IT CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

Creating the WebService program for Account creation

Step 8:

Open the netbeans 6.1

Creat a new web project.

Step 9:

Type the project Name as MyAccount

Click on the next button.

Step 10:

Select the server as Glassfish

Click on the Next and then finish button.

Step 11:

It creates a Web Project named MyAccount.

Creating the WebService

Step 12:

 Right Click on the project MyAccount  Select New-->WebService .

Step 13:

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

Click on the Finish button

Step 14:

It creates a WebService application in design view

Click on the Add operation.

Step 15:

[Department of CSE] 34

PERIPERIIT IT CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

In the dialog box type all parameter names. Also select the appropriate data type.

Click on Ok as shown.

Step 16:

It creates a WebService application

Click on the source tab.

Step 17:

Now create the database source Right Click in the source code of myaccount.java

Select the Enterprise Resources-->Use Database.

Step 18:

In the choose database select the Add button .

Step 19:

 It opens a Add Data Source Reference.  Type the Reference Name as data1  For Project Data Sources Click on the Add button.

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

Step 22:

 It creates the datasource data1 with the resource name as data1 in the code  Edit the code and give the database connection, statement for the mysql connectivity as shown below.

[Department of CSE] 35

PERIPERIIT IT CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

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(?,?,?,?,?,?,?)"); 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) {

[Department of CSE] 36

PERIPERIIT IT CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

System.out.println(e.getMessage()); } return "record inserted"; } }

Step 23:

 Now deploy the project  Right click on the project  Select Undeploy and Deploy.  It builds and deploys the MyAccount Web project on the server.

Step 24:

 After deploying now we can test the Web Service created  Right click on the myaccount webservice  Select Test Web Service .

Step 25:

 It runs the deployed webservice in the firefox browser.  Type the value and click on the insert button.

Step 26:

 After clicking on the insert button it insert the values into the login table  It open new window and displays the Metrhod parameters, SOAP request and response.

Step 27:

Check the data in the database table

 In the service tab select the mysql connection  In its table node right click on the table login  Select the view data.

Step 27:

 It opens a new window  Then displas the data.

Making the client of the WebService

Step 28:

[Department of CSE] 37

PERIPERIIT IT CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

 Create a new Web Project  Type the name as MyAccountClient.

Step 29:

 Click on the next button  Select the server as glassfish .

Step 30:

 Click on the finish button  It creates a web rpoject with a index.jsp file  In the index.jsp design it with form and all its fileds  Give the form action as Client.jsp.|

Create WebService Client

Step 1:

 Right Click on the MyAccountClient  Select WebService Client .

Step 2:

In the dialog box click on the browse button.

Step 3:

Select the myaccount webservice. Click on the OK button as shown

Step 4:

Now project is containing the WSDL file url.

Click on the Ok button. Step 5: Right Click in the Client.jsp Select Web Service Client Resources-->Call WebService Operation.

Step 5:

Select the insert operation .

Step 6:

[Department of CSE] 38

PERIPERIIT IT CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

After insert opoeration the code.

Step 7:

Deploy the MyAccountClient

Right Click and select Undeplo and Deploy.

Step 8:

After deployment run the project.

Right Click and select the run.

Step 9:

It runs the index.jsp in the browser .

Put the data and click on the ok button

Step 10:

After this click values get inserted in the database table

The message comes as record inserted

Step 11: See the data inserted in the table. In the service tab select the connection created for mysql. In the table node select the login

Right Click and select the view data.

Step 12:

It displays the record inserted

COMMUNICATING OBJECT DATA: SOAP

What is SOAP?

 SOAP stands for Simple Object Access Protocol  SOAP is a communication protocol  SOAP is for communication between applications  SOAP is a format for sending messages

[Department of CSE] 39

PERIPERIIT IT CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

 SOAP communicates via Internet  SOAP is platform independent

Why SOAP?

It is important for application development to allow Internet communication between programs. Today’s applications communicate using Remote Procedure Calls (RPC) between objects like DCOM and CORBA, but HTTP was not designed for this. RPC represents a compatibility and security problem; firewalls and proxy servers will normally block this kind of traffic. A better way to communicate between applications is over HTTP, because HTTP is supported by all Internet browsers and servers. SOAP was created to accomplish this. SOAP provides a way to communicate between applications running on different operating systems, with different technologies and programming languages. SOAP is a W3C Recommendation Syntax Rules

Here are some important syntax rules:

 A SOAP message MUST be encoded using XML  A SOAP message MUST use the SOAP Envelope namespace  A SOAP message MUST use the SOAP Encoding namespace  A SOAP message must NOT contain a DTD reference  A SOAP message must NOT contain XML Processing Instructions

ENVELOPE

HEAD BODY

FAULT

Structure of SOAP SOAP Message

[Department of CSE] 40

PERIPERIIT IT CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

... ... ... SOAP Envelope Element

The required SOAP Envelope element is the root element of a SOAP message. This element defines the XML document as a SOAP message.

Example ... Message information goes here ...

The xmlns:soap Namespace

Notice the xmlns:soap namespace in the example above. It should always have the value of: "http://www.w3.org/2001/12/soap-envelope". The namespace defines the Envelope as a SOAP Envelope. If a different namespace is used, the application generates an error and discards the message. The encodingStyle Attribute

The encodingStyle attribute is used to define the data types used in the document. This attribute may appear on any SOAP element, and applies to the element's contents and all child elements.

A SOAP message has no default encoding.

Syntax soap:encodingStyle="URI"

Example

[Department of CSE] 41

PERIPERIIT IT CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

... Message information goes here ... SOAP Header Element

The optional SOAP Header element contains application-specific information (like authentication, payment, etc) about the SOAP message.

If the Header element is present, it must be the first child element of the Envelope element.

234 ...... The example above contains a header with a "Trans" element, a "mustUnderstand" attribute with a value of 1, and a value of 0.

SOAP defines three attributes in the default namespace ("http://www.w3.org/2001/12/soap- envelope"). These attributes are: mustUnderstand, actor, and encodingStyle. The attributes defined in the SOAP Header defines how a recipient should process the SOAP message. The must Understand Attribute

The SOAP mustUnderstand attribute can be used to indicate whether a header entry is mandatory or optional for the recipient to process.

If you add mustUnderstand="1" to a child element of the Header element it indicates that the receiver processing the Header must recognize the element. If the receiver does not recognize the element it will fail when processing the Header.

Syntax soap:mustUnderstand="0|1"

[Department of CSE] 42

PERIPERIIT IT CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

Example 234 ...... The actor Attribute

A SOAP message may travel from a sender to a receiver by passing different endpoints along the message path. However, not all parts of a SOAP message may be intended for the ultimate endpoint, instead, it may be intended for one or more of the endpoints on the message path.

The SOAP actor attribute is used to address the Header element to a specific endpoint.

Syntax soap:actor="URI"

Example 234 ......

The encodingStyle Attribute

The encodingStyle attribute is used to define the data types used in the document. This attribute may appear on any SOAP element, and it will apply to that element's contents and all child elements.

A SOAP message has no default encoding.

[Department of CSE] 43

PERIPERIIT IT CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

Syntax soap:encodingStyle="URI" SOAP Body Element

The required SOAP Body element contains the actual SOAP message intended for the ultimate endpoint of the message.

Immediate child elements of the SOAP Body element may be namespace-qualified.

Example Apples

The example above requests the price of apples. Note that the m:GetPrice and the Item elements above are application-specific elements. They are not a part of the SOAP namespace.

A SOAP response could look something like this:

1.90 A SOAP Example A SOAP request: POST /InStock HTTP/1.1 Host: www.example.org Content-Type: application/soap+xml; charset=utf-8 Content-Length: nnn

[Department of CSE] 44

PERIPERIIT IT CS8651-INTERNET PROGRAMMING JEPPIAAR SRR ENGINEERING COLLEGE

IBM The SOAP response:

HTTP/1.1 200 OK Content-Type: application/soap+xml; charset=utf-8 Content-Length: nnn 34.5

[Department of CSE] 45