IP Unit-5-1
IP Unit-5-1
AJAX: AJAX client server architecture – XMLHttpRequest object – Call back methods; Web
Services: Introduction – Java Web Services basic – Creating, Publishing, Testing and
Describing a web service (WSDL) – Consuming a web service, Database driven web service
– SOAP.
DISADVANTAGES:
1. It can increase design and development time.
2. More complex than building classic web application.
3. Less Accessibility: because all browsers do not completely support Javascript and
xmlHttpRequest object.
4. Due to security constraints, you can only use it to access information from the host
that served the initial page. If you need to display information from another server, it
is not possible within the AJAX.
The following figure depicts the interactions between the client and the server in traditional
web applications.
Step 1: The user fills in the form’s fields, and then submits the form.
Step 2: The browser generates a request to the server, which receives the request and process
it.
2
Step 3: The server generates and sends a response containing the exact page that the browser
will render.
Step 4: Browser loads the new page and temporarily makes the browser window blank. The
client waits for the server to respond and reloads the entire page.
Such a Synchronous request is being processed on the server; the user cannot interact with
the client web page.
The following figure depicts the interactions between the client and the server in Ajax web
applications. Ajax adds a layer between the client and the server to manage communication.
Step 1: When the user interacts with the page, the client creates an XMLHttpRequest object
to manage a request.
Step 2: The XMLHttpRequest object sends the request to the server and awaits for
response. The requests are asynchronous so the user can continue interacting with
the application while the server processes the earlier request concurrently.
Step 3 & 4: Other user interactions results in additional requests to the server.
Step 5: Once the server responds, the XMLHttpRequest object that issued the request calls
a client-side function (also known as callback function) to process the data returned
by the server.
Step 6: This callback function performs the partial page update to display the data in the
existing web page without reloading the entire page.
3
The following figure depicts the interactions between the client and the server in Ajax web
applications. Ajax adds a layer between the client and the server to manage communication.
Step 1: When the user interacts with the page, the client creates an XMLHttpRequest object
to manage a request.
Step 2: The XMLHttpRequest object sends the request to the server and awaits for
response. The requests are asynchronous so the user can continue interacting with
the application while the server processes the earlier request concurrently.
Step 3 & 4: Other user interactions results in additional requests to the server.
Step 5: Once the server responds, the XMLHttpRequest object that issued the request calls
a client-side function (also known as callback function) to process the data returned
by the server.
Step 6: This callback function performs the partial page update to display the data in the
existing web page without reloading the entire page.
4
WORKING OF AJAX:
➢ XMLHttpRequest Object:
The XMLHttpRequest Object is the layer between the client and the server that creates and
manages asynchronous requests in Ajax applications. All modern browsers support the
XMLHttpRequest object (IE5 and IE6 use an ActiveXObject).
variable=new XMLHttpRequest();
Old versions of Internet Explorer (IE5 and IE6) use an ActiveX Object:
variable=new ActiveXObject("Microsoft.XMLHTTP");
PROPERTIES:
Property Description
onreadystatechange Stores the callback function – the event handler that gets called
when the server responds.
readystate Holds the status of the XMLHttpRequest. Changes from 0 to 4:
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
status 200: "OK"
404: Page not found
statusText Additional information on the request’s status. It is used to
display error messages to the user when the request fails.
response Returns the response received from the server
responseText Text that is returned to the client by the server
responseXML If the server’s response is in XML format, this property contains
the XML document.
METHODS:
Method Description
open(method,url,async) Specifies the type of request, the URL, and if the request should
be handled asynchronously or not.
method: the type of request: GET or POST
url: the location of the file on the server
async: true (asynchronous) or false (synchronous)
send sends the request to the server
setRequestHeader Alters the request header
getResponseHeader Returns the header data that precedes the response body
getAllResponseHeaders Returns an array that contains all the headers data that precedes
the response body
abort Cancels the current request.
6
➢ Callback Functions:
Example:
ajaExample.html
<html>
<head>
<style>
div {
border-style:solid;
border-color:blue;
border-width:5px
}
</style>
<script type="text/javascript">
var req;
function getContent(url)
{
try
{
if(window.XMLHttpRequest)
{
req=new XMLHttpRequest(); // Creating XMLHttpRequest Object
}
else
{
req=new ActiveXObject("Microsoft.XMLHTTP");
}
req.onreadystatechange=callbackfun; // Callback function call to handle response
req.open("GET",url, true); // open the connection to the requested resource
req.send(); // send the request to the server
}
catch(e) { alert("Request failed"); }
}
7
function callbackfun()
{
if(req.readyState==4 && req.status==200)
Callback
{
Method
document.getElementById('display').innerHTML=req.responseText;
}
}
</script>
</head>
<body>
<h3><center>
<input type="button" value="Flowers" onclick="getContent('flowers.html')">
<input type="button" value="Fruits" onclick="getContent('fruits.html')">
<div id="display" ><h2>Let AJAX change this text and picture</h2></div><br>
</center></h3>
</body></html>
Flowers.html
<html>
<body><br>
<img src="flower1.jpg" width="100" height="100">
<img src="flower2.jpg" width="100" height="100">
<img src="flower3.jpg" width="100" height="100">
</body>
</html>
Fruits.html
<html>
<body>
<br>
<img src="fruit1.jpg" width="100" height="100">
<img src="fruit2.jpg" width="100" height="100">
<img src="fruit3.jpg" width="100" height="100">
</body>
</html>
8
Output:
9
Definition: A Web Service is a software component stored on one computer that can be
accessed via method calls by an application (or other software component) on another
computer over a network. These software components are not directly used by the end-users.
Web Services communicate using technologies such as XML, SOAP (an XML based
protocol) and HTTP.
Using a web service from a client application is known as consuming a web service;
10
Client Server
Client Proxy
Internet Web Service
Code Object
Steps:
Step 1: Right click on the project name and select New > Web Service…
Step 2: Specify the name of the web service in the Web Service name field.
Step 3: Specify the package name in the package filed.
Step 4: Click Finish.
12
IntegerOpr.java
package com.ip;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
@WebService()
public class IntegerOpr
{
/* Web service operation */
@WebMethod(operationName = "Add")
public int Add(@WebParam(name = "n1") int n1, @WebParam(name = "n2") int n2)
{
int sum = n1+n2;
return sum;
}
}
Annotations used:
4. Publishing the web service (Build, Deploy and Run the Project)
Build and publish (deploy) the web service so that the client can consume its service.
Step 1: Right click on the project name and select Build Project to compile the source codes
in the project.
Step 2: When the project compiled successfully, select Deploy Project to deploy the project
to the GlassFish server.
5. Testing the Web service.
In the IDE's Projects tab, expand the Web Services node of the IntegerOpr Application
project. Right-click the IntegerOpr node, and choose Test Web Service.
14
Main.java
package mywebclient;
public class Main {
<types>
data type definitions........
</types>
<message>
definition of the data being communicated....
</message>
<portType>
set of operations......
</portType>
<binding>
protocol and data format specification....
</binding>
</definitions>
WSDL Types
The <types> element defines the data types that are used by the web service.
WSDL Messages
The <message> element defines the data elements of an operation.
Each message can consist of one or more parts (parameters of method).
WSDL Ports
The <portType> element is the most important WSDL element.
It describes a web service, the operations that can be performed, and the messages that are
involved.
Operation Types
The request-response type is the most common operation type, but WSDL defines four types:
Type Definition
The operation can receive a message but will not return a
One-way
response
17
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
The operation can send a message but will not wait for a
Notification
response
WSDL Bindings
The <binding> element defines the data format and protocol for each port type.
<Service> - This element specifies the name for overall web service.
Example: WSDL document for a web service that add two integers:
<definitions name="IntegerOprService">
<types>
<xs:schema>
<xs:element name="Add" >
<xs:element name="AddResponse" type="tns:AddResponse" />
<xs:complexType name="Add">
<xs:sequence>
<xs:element name="n1" type="xs:int" />
<xs:element name="n2" type="xs:int" />
</xs:sequence>
</xs:complexType>
<xs:complexType name="AddResponse">
<xs:sequence>
<xs:element name="return" type="xs:int" />
</xs:sequence>
</xs:complexType>
</xs:schema>
</types>
<message name="Add">
<part name="parameters" element="tns:Add"/>
</message>
<message name="AddResponse">
<part name="parameters" element="tns:AddResponse"/>
18
</message>
<portType name="IntegerOpr">
<operation name="Add">
<input message="tns:Add"/>
<output message="tns:AddResponse"/>
</operation>
</portType>
<service name="IntegerOprService">
<port name="IntegerOprPort" binding="tns:IntegerOprPortBinding">
<soap:address location="http://localhost:8080/IntegerOpr/IntegerOprService"/>
</port>
</service>
</definitions>
Advantages of WSDL:
1. WSDL is platform independent.
2. WSDL provides a structured approach to define web service.
3. A client can locate a web service and invoke its public methods with (or) without
programming efforts.
4. Changes can be made in WSDL documents dynamically.
Disadvantages of WSDL:
Though a wsdl provides details on how to invoke a service, it does not contain
information about the use of the service. Programmer should be aware about the use of a
service.
19
Simple Object Access Protocol (SOAP) is a protocol based on XML to facilitate remote
procedure calls over HTTP. It is a W3C recommendation used by the web service for
exchanging information between web service clients and web services.
It is a wire protocol because it transmits request-response message “along the wire”.
<?xml version="1.0"?>
<soap:Envelope
xmlns:soap="http://www.w3.org/2001/12/soap-envelope"
soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding">
<soap:Header>
... Envelop
</soap:Header>
<soap:Body>
... Head Body
<soap:Fault>
...
</soap:Fault> Fault
</soap:Body>
</soap:Envelope>
Syntax Rules:
Example:
SOAP Request
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
<S:Header/>
<S:Body>
<ns2:Add xmlns:ns2="http://ip.com/">
<n1>40</n1>
<n2>50</n2>
</ns2:Add>
</S:Body>
</S:Envelope>
SOAP Response
SOAP Advantages:
1. Platform independent.
2. Uses XML to send and receive messages.
3. SOAP is also a simple way to accomplish remote object/component/service
communications.
4. Uses standard internet HTTP protocol.
5. SOAP runs over HTTP, which eliminates firewall problems.
6. A protocol for exchanging information in a decentralized and distributed environment.
Disadvantages:
Database driven web service is one that uses database for collecting and storing
information. It interacts with the database based upon request issued by the web service
client.
AirLineInfo.java
package com.ip;
import java.sql.*;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
23
@WebService()
public class AirLineInfo {
Connection conn;
Statement stmt;
ResultSet rs;
String result=null;
@WebMethod(operationName = "getInfo")
public String getInfo(@WebParam(name = "FID")
int FID) {
try
{
//Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn=DriverManager.getConnection("jdbc:odbc:Air","","");
stmt=conn.createStatement();
rs=stmt.executeQuery("select * from AirInfo where FId ="+FID);
if(rs.next())
{
result="Flight Id:"+rs.getInt(1);
result+="-->Name:"+rs.getString(2);
result+="-->Source:"+rs.getString(3);
result+="-->Destination:"+rs.getString(4);
result+="-->Capacity:"+rs.getInt(5);
}
else
result="Invalid Flight ID";
}
catch(Exception e){}
return result;
}
}
4. Publishing the web service (Build, Deploy and Run the Project)
Build and publish (deploy) the web service so that the client can consume its service.
Step 1: Right click on the project name and select Build Project to compile the source codes
in the project.
Step 2: When the project compiled successfully, select Deploy Project to deploy the project
to the GlassFish server.
24
AirServlet.java
package mypack;
import com.ip.AirLineInfoService;
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import javax.xml.ws.WebServiceRef;
@WebServlet(name="AirServlet", urlPatterns={"/AirServlet"})
@WebServiceRef ( wsdlLocation =
"WEB-INF/wsdl/localhost_8080/AirLines/AirLineInfoService.wsdl")
private AirLineInfoService service;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
int fid=Integer.parseInt(request.getParameter("fid"));
out.println("<html><body>");
out.println("<center>");
25
5.2.6: UDDI
UDDI is an XML-based standard for describing, publishing, and finding web services.
• A set of WSDL port type definitions for manipulating and searching that
registry.
• Relationship between SOAP, WSDL & UDDI:
Registry
(UDDI) Publish
Find
(WSDL)
(SOAP)
Service
Service
Provider
Requestor
Bind
(SOAP)
UDDI Elements:
A business or a company can register three types of information into a UDDI registry. This
information is contained in three elements of UDDI.
White Pages
White pages contain:
• Basic information about the company and its business.
• Basic contact information including business name, address, contact phone number,
etc.
Yellow Pages
• Yellow pages contain more details about the company
Green Pages
Green pages contain technical information about a web service. A green page allows
someone to bind to a Web service after it's been found. It includes:
• The various interfaces
• The URL locations
• Discovery information and similar data required to find and run the Web service.
UDDI Benefits
1. It delivers visibility when identifying which services within the organization can be
reused to address a business need.
28