Sie sind auf Seite 1von 17

UNIT V

WEBSERVICE

→ Webservice is a s/w designed independent of specific hardware or software

→ xposing it XML

Eg: webservice

 credit card validation

 weather forecast system

 currency converter

Elements of webservice:

1) UDDI  Univ description and discovery integration

 provide a directory of webservices

 Registering webservices can be registered

2) WSDL  Web Services descriptor Language

 It is used to describe the webservices

3) SOAP  Simple Object Access Protocol

It sends the request and gets the response

It is XML based ptrl which allows xchange of messaging over HTTP

JWSDP  JAVA webservices developer package

JAXRPC  JAVA API xml with Remote procedure call

JWSDP  JAVA webservice developer pack

How to write with NOTEPAD:

1) Install JWSDP
download → exe file

2) Set the environment variables

webcontainer  Tomcat get install

1) JWSDP_HOME

c:\jwsdp-2.0

2) CATALINE_HOME

c:\Tomcat50-jwsdp

3) CLASS_PATH

c:\Tomcat . . . .\lib\servlet-api.jar

Writing a WS:

1) Create a folder c:\Hellomessage with web-INF inside and two more folders name src and

classes

[[***Art***]]

2) For writing WS interface is mandatory

3) → interface must extend

java.rmi.Remote interface

→ every method in the interface must throw java.rmi.RemoteException

remote method invokation

→ Interface should contain primitive datatype int, boolean, string

1) Create interface Myinterface.java

[[***Art***]]

MyInterface.java
5) package hellomsg;

import.java.rmi.RemoteException;

public interface Myinterface extends java.rmi.Remote

public string HelloFun (string hellostring)

throws java.rmi.Remote Exception

5) C:\HelloMessage\web-inf> javac-d.classes

srd hellomsg\My interface.java

6) package hellomsg;

public class MyImplementation implements

MyInterface

public string Hellofun (StringHelloString)

return “welcome to ws”

7) c:\Hello msg\WEB-INF> javac-d classes src\hellomsg\Myimplementation.java

8) create config.xml. inside c:\hellomessage

It specify the name of WSDL

[[***Art***]]

<?xml>
<configuration mlns = “http://java.oracle.com/xml/ns/jax-rpc/ri/config>

<service name = “simple hellomessage” package name = “hellomessage”/>

<interface name = “hellomsg.Myinterface”/>

</configuration>

9) c:\hellomessage\

wscompile-defined-d WEB-INF-classpath WEB-INF/classes.-model WEB-NF/model.xml.gz

config.xml

Command to generating WSDL

-d  specify WSDL must be generated in WEB-INF classes

-model  internal DS which describes the service

gz  compressed file

ws compile  used to generate the WSDL file

10) c:\HelloMessage\WEB-INF\jaxrpc-ri.xml

deployment descriptor (web.xml)

name, classes, URL pattern

11) <?xml>

<webservices xmlns = “http://java.oracle.com/xml/ns/jax-rpc/ri/dd” use pattern Base = “/Hello”>

nance of the var file to be deployed web archive file collection of different web tech file.

<endpoint Mapping endpoint Name = “Hello Msg” Urlpattern = “/hello”/>

</webservice>

12) Consume the WS

web.xml

c:\HelloMessage>“jar cf Hello-temp.rar
WEB-INF

Cf = create file

C:\Hellomessage>wsdeploy-o

Hello.war Hello-temp.war

copy → tomcat → webapps → directory

Open the browser url:http://localhost:8080/hello/hello.war

Consume the WS

1) Creating WS client

2) Create folder name Hellomessage client under webapps

[[***Art***]]

2) WS compile -gen - keep -d classes -s

Source config.xml

Skeleton classes → consume the webservices

stub → webservices

-gen  Create classes in directory also message client/WEB-INF/classes

Classes:

→ MyInterface_stub

→ Simple Hellomsg – Impl → Service class

→ Simple Hello Message – Seriallar Registery MyInterface_Stub  Interface

→ MyInterface_Hellofun – Request struct_SOAP Builder.

→ MyInterface_Hellofun_Response struct_SOAP Builder.

Hellomsgclient – java

import javax.servlet.*;
import javax.servlet.http.*;

public class Hellomsgclient extends Http servlet

public void doGET (HttpServletRequest response, HttpServletResponse throws Servlet

Exception_Io Exception

Simple Hello Message_Impl Service = new Simple Hello Message_Impl( );

MyInterface stub = Service.getMy InterfacePort ( );

String S = Stub.HelloFun (“Hello WS”);

println (s);

3) Running:

xml → Hellomsgclient

Restart Tomcat Server

http://localhost:8080/HelloMsgClient

WSDL

Web Serv Descriptor Language

It is based on xml

It is used to desc the webserv and the method for accusing it.

It is W3C recommendation

Elements:

→ Types  Specify the datatype of symbols used by the Webservices


→ Message  Specify the msg used by Webservices

 Message define part of the element along with it datatype

Eg: name = “MyInterface_HelloFun response

→ Port type  define operation performed by WS

→ Binding  defines msg format details of the ptrl

No response  one-way

Get both  request-response

Send and wait  Solicit-response

Send and no wait  Notification

<?xml version = “1.0”>

< name = “Simple HelloMessage” target Namespace = “http://tempins.org/wsdl”/>

<types/>

<message name = “MyInerface_HelloFun”>

<path name = “String” – type = “*sd.string”/>

</message>

<port type name = “MyInterface”>

<operation name = “HelloFun”>

<InputMessage = “tns: MyInterface_HelloFun”/>

<OutputMessage = “tns: MyInterface_HelloFun Response”/>

</operations>

</port type>

<binding name = “MyInterface Binding” type = “tns: MyInterface”>

<SOAP: binding transport = “http://scheman.xmlsoap.org/soap/http” style = “rpc”/>


<operation name = “HelloFun”

<input>

<soap.body namespace = “http://tempins.org/wsdl”/>

</input>

<output>

<soap.body namespace = “http://tempins.org/wsdl”/>

</output>

</binding>

</definition>

SOAP

Simple Object Access ptrl

→ For changing inf WS

→ Based xml

→ w3c std.

→ xchang of i/f is done over http

→ platform & Lang independent ptrl

Structure:

[[***Art***]]

Envelope: It is root of SOAP document

It identifies the msg as SOAP msg.

Two attributes NameSpace, Encoding


xmlns: Soap = “http//www.w3.org/2001-12/soap-envelope”.

Soap: encoding style = “http//www.w3.org/2001/12/soap-encoding”.

Head: Optional three attributes

1. must understand  0(optional) or 1(receives should process the header)

2. actor  url for end point

3. encoding style  define datatype used in particular document

Body: SOAP msg for endpoint where WSDL stored

Fault: [optional]

It is used to represent the error code.

Fault code – 404

Fault Message – Forbidden

<?xml version = “1.0”>

<SOAP-ENV: Envelope xmlns: SOAP-ENV = “http://www.w3.org/2001/12/SOAP-envelope”

SOAP-Encoding style = “http//w3.org/2001/12/SOAP-Encoding>

<SOAP-ENV: Body xmlns im = “http://www.mywebsite.com/mycreation>

<m: Getdetails>

<m. name>Kevin</m. name>

</m. Getdetails>

</SOAP-ENV: body>

</SOAP-ENV: Envelope>

Database Driven web service from an application

1.CONSTRUCT A DATABASE FOR AIRLINE RESERVATION


SQL> desc airways_table
Name Null? Type
______________________________________________
NUM NUMBER(10)
NAME VARCHAR2(15)
START_FROM VARCHAR2(15)
DEST VARCHAR2(15)

SQL> select * from airways_table;

NUM NAME START_FROM DEST


_____________________________________________________
1001 british airways pune chennai
2001 air india mumbai pune
3001 indian airlines chennai pune
2002 airindia chennai mumbai
1002 british airways chennai pune
1003 british airways mumbai pune
3002 indian airlines pune mumbai
2003 airindia pune mumbai
3003 indian airlines pune mumbai

9 rows selected.

2. CONSTRUCT AIRLINE RESERVATION WEB SERVICE


package airinfo;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import java.sql.*;

@WebService( name="Test", serviceName = "TestDB" )


public class TestDB {

/**
* Web service operation
*/
@WebMethod(operationName = "getInfo")
public String getInfo(@WebParam(name = "src")
String src, @WebParam(name = "dest")
String dest) {
String str="";
try
{Class.forName("oracle.jdbc.driver.OracleDriver");
System.out.println("inside testdb");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@//192.168.9.185:1521/cse","system","ma
nager");

Statement s=con.createStatement();
if(src.equals("mumbai"))
{
if(dest.equals("pune"))
s.executeQuery("SELECT * FROM airways_table WHERE Start_from='mumbai' AND
Dest='pune'");
else if(dest.equals("chennai"))
s.executeQuery("SELECT * FROM airways_table WHERE Start_from='mumbai' AND
Dest='chennai'");
}
else if(src.equals("pune"))
{
if(dest.equals("mumbai"))
s.executeQuery("SELECT * FROM airways_table WHERE Start_from='pune' AND
Dest='mumbai'");
else if(dest.equals("chennai"))
s.executeQuery("SELECT * FROM airways_table WHERE Start_from='pune' AND
Dest='chennai'");
}
else if(src.equals("chennai"))
{
if(dest.equals("pune"))
s.executeQuery("SELECT * FROM airways_table WHERE Start_from='chennai' AND
Dest='pune'");
else if(dest.equals("Mumbai"))
s.executeQuery("SELECT * FROM airways_table WHERE Start_from='chennai' AND
Dest='mumbai'");
}
ResultSet rs=s.getResultSet();
str+="<table border=1>";
while(rs.next())
{
str+="<tr><b>";
str+="<td>";
str+=rs.getString("name");
str+="</td>";
str+="</tr></b>";
}
str+="</table>";

}catch(ClassNotFoundException ex)
{
System.out.println(ex);
}
catch(SQLException ex)
{
System.out.println(ex);
}
return str;
}

}
3.CONSTRUCT AIRLINE RESERVATION CLIENT

a)index.jsp

<html>
<head>
<title>AIRLINE RESERVATION SYSTEM</title>
</head>
<body bgcolor=”khaki”>
<center>
<h4>Travel Agent should fill up following information to get information about the
Airline</h4>
<form name=”form1” method=GET action =”reserve.jsp”>
<table>
<tr>
<td><b>Source city: </b></td>
<td><input type=”text” name=”Src_name” size=”20” value=””></td>
</tr>
<tr>
<td><b>Destination city: </b></td>
<td><input type=”text” name=”Dest_name” size=”20” value=””></td>
</tr>
<tr>
<td><input type=”submit” value=”Submit”></td>
</tr>
</table>
</form>
</center>
</body>
</html>

b)reserve.jsp

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


Airline Seat Confirmation
<%
String a1=request.getParameter("Src_name");
String a2=request.getParameter("Dest_name");
%>
<%-- start web service invocation --%>

<%
try {
air.TestDB_Service service =new air.TestDB_Service();
air. TestDB port = service.get TestDB Port();
String result = port.get(a1, a2);
%>
<%
} catch (Exception ex) {
ex.printStackTrace();
}
%>

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

AIRLINE RESERVATION
Result is
Airline Seat Confirmation
indian airlines
british airways

AJAX
What is AJAX?
• AJAX stands for Asynchronous Javascript And XML
• AJAX is not a programming language
• AJAX is a way of using existing standards (JavaScript and XML) to make more interactive web
applications
• AJAX was popularized in 2005 by Google (with Google suggest)

An AJAX Application
• Recall the standard HTTP transaction
1. Client opens connection to server
2. Client sends request to server
3. Server sends reply to client
4. Client and server close connection
• After Step 4, the client renders the document and this may include running some JavaScript
• In an AJAX application, the JavaScript code then communicates with the server behind the scenes.
Communication with the server takes place asynchronously, and transparently to the user
• Data is exchanged with the server without the need for a page reload
• This is accomplished through a special kind of HTTP request

How AJAX Works


Setting up an AJAX Transaction
• Create an XMLHTTPRequest object
• Set up the request's onreadystatechange function
• Open the request
• Send the request

EXAMPLE

create input page to receive any text or number

In this page, we have created a form that gets input from the user. When user clicks on the showTable
button, sendInfo() function is called. We have written all the ajax code inside this function.

We have called the getInfo() function whenever ready state changes. It writes the returned data in the web page
dynamically by the help of innerHTML property.

table1.html
<html>  
<head>  
<script>  
var request;  
function sendInfo()  
{  
var v=document.vinform.t1.value;  
var url="index.jsp?val="+v;  
  
if(window.XMLHttpRequest){  
request=new XMLHttpRequest();  
}  
else if(window.ActiveXObject){  
request=new ActiveXObject("Microsoft.XMLHTTP");  
}  
  
try  
{  
request.onreadystatechange=getInfo;  
request.open("GET",url,true);  
request.send();  
}  
catch(e)  
{  
alert("Unable to connect to server");  
}  
}  

function getInfo(){  
if(request.readyState==4){  
var val=request.responseText;  
document.getElementById('amit').innerHTML=val;  
}  
}  
  
</script>  
</head>  
<body>  
    <marquee><h1>This is an example of ajax</h1></marquee>  
<form name="vinform">  
<input type="text" name="t1">  
<input type="button" value="ShowTable" onClick="sendInfo()">  
</form>  
  
<span id="amit"> </span>  
  
</body>  
</html>  

create server side page to process the request

In this jsp page, we printing the table of given number.

index.jsp
<%  
int n=Integer.parseInt(request.getParameter("val"));  
  
for(int i=1;i<=10;i++)  
out.print(i*n+"<br>");  
  
%>  

web.xml
<?xml version="1.0" encoding="UTF-8"?>  
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"   
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">  
  
    <session-config>  
        <session-timeout>  
            30  
        </session-timeout>  
   </session-config>  
    <welcome-file-list>  
      <welcome-file>table1.html</welcome-file>  
        </welcome-file-list>  
    </web-app>  

Advantages of AJAX
AJAX Concept
Before you starting AJAX you'll need to have a strong knowledge of JavaScript. AJAX is not a difficult, you can
easy implement AJAX in a meaningful manner. Some IDE are help us to implement AJAX.

Speed
Reduce the server traffic in both side request. Also reducing the time consuming on both side response.

Interaction
AJAX is much responsive, whole page(small amount of) data transfer at a time.

XMLHttpRequest
XMLHttpRequest has an important role in the Ajax web development technique. XMLHttpRequest is special
JavaScript object that was designed by Microsoft. XMLHttpRequest object call as a asynchronous HTTP
request to the Server for transferring data both side. It's used for making requests to the non-Ajax pages.

Asynchronous calls
AJAX make asynchronous calls to a web server. This means client browsers are avoid waiting for all data
arrive before start the rendering.

Form Validation
This is the biggest advantage. Form are common element in web page. Validation should be instant and
properly, AJAX gives you all of that, and more.

Bandwidth Usage
No require to completely reload page again. AJAX is improve the speed and performance. Fetching data from
database and storing data into database perform background without reloading page.

Disadvantages of AJAX
1. AJAX application would be a mistake because search engines would not be able to index an AJAX
application.

2. Open Source: View source is allowed and anyone can view the code source written for AJAX.

3. ActiveX requests are enabled only in Internet Explorer and newer latest browser.

4 The last disadvantage, XMLHttpRequest object itself. For a security reason you can only use to access
information from the web host that serves initial pages. If you need to fetching information from another server,
it's is not possible with in the AJAX.

Das könnte Ihnen auch gefallen