The tutorial will have two sections :
1. A simple java method exposed as a webservice ( using java embedded webserver. No need of axis, tomcat etc.,)
2. A simple html page which will invoke the webservice ( no need of php , jsp etc., ) with a simple xmlhttp request / reposnse.
Two steps for Creating and Publishing Webservice using jax-ws:
1) create a java class and add methods which will be exposed as webservices. To make normal java methods as webservices we have to annotate the methods using @WebMethod annotaiion. Java class must be annotated with @WebService annotation. To Customize the parameter names in the request use @WebParam annotation
Example: This example exposes the webservices to calculate the area of suare and rectangle.
package com.example.ws;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import javax.xml.ws.Endpoint;
@WebService
public class Area {
@WebMethod
public double square(@WebParam(name="side") double side)
{
return side * side;
}
@WebMethod
public double rectangle(@WebParam(name="length") double length,@WebParam(name="breadth") double breadth)
{
return length * breadth;
}
public static void main(String[] args) {
Area area = new Area();
String url = "http://localhost:8090/area"; // end point of webservice.
System.out.println(url+"?wsdl");
Endpoint.publish(url, area); // publishing the webservice
}
}
apt -d . com\example\ws\Area.java
This command will generate the required wrapper classes one correspoding to request and other corresponding to response.
Now your webservice is ready to use. Just run the class com.example.ws.Area
you can view the wsdl of the service using url http://localhost:8090/area?wsdl
Hope you are getting it running.
Calling webservice from browser using XMLHttpRequest
The webserive exposed can be accessed using soap request sending from browser
<html>
<head>
<script language="javascript">
function call()
{
var side = sideid.value;
var req = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:web=\"http://ws.example.com/\"><soapenv:Body><web:square><side>" + side+ "</side></web:square></soapenv:Body></soapenv:Envelope>";
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
var reqXML = xmlDoc.loadXML(req);
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var response = xmlhttp.responseXML;
alert(response.selectSingleNode(".//return").text);
}
}
var soapaction = "http://ws.example.com/square";
xmlhttp.open("POST","http://localhost:8090/area?wsdl",true);
xmlhttp.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xmlhttp.setRequestHeader("SOAPAction", soapaction);
xmlhttp.send(req);
}
</script>
</head>
<body>
Side Length: <input type="text" id="sideid"></input>
<button onclick="call();">area of square</button>
</body>
</html>
Donot forget to give your comments /suggestions and refer to your friends.