Let’s start with Hello world example. We are going to see
Hello world example by both Document style as well as RPC style.
HelloWorld.java – Service
Interface
package com.sri.ws;
import javax.jws.WebMethod;
import
javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import
javax.jws.soap.SOAPBinding.Style;
@WebService
@SOAPBinding(style = Style.DOCUMENT)
public interface HelloWorld{
@WebMethod
String
sayHelloToUser(String name);
}
HelloWorldImpl.java –
Implementation Class
package com.sri.ws;
import
javax.jws.WebService;
//Service Implementation
@WebService(endpointInterface = "com.sri.ws.HelloWorld")
public class HelloWorldImpl implements HelloWorld{
@Override
public String
sayHelloToUser(String name) {
return "Hello Mr. " + name+" !!!";
}
}
Create a package named com.sri.ws and drop the above two
files in it.
@WebService – Annotation used for making a normal class as a
web service class. By default all the methods of this class are service
operations. @WebMethod is optional. If you don’t want to expose a method as
service operation then use @WebMethod(exclude=true). Optional tag @SOAPBinding
can be used to define whether a service is Document type or RPC type.
For writing the web service in the RPC style use the
following annotation in the HelloWorld.java interface
@SOAPBinding(style = Style.RPC)
The
Document style contains the SOAP body in the XML document can be validated
against the predefined XML schema. In RPC, web services use method name and
parameters to generate XML structure.
Let’s write a class to publish the service we created.
HelloWorldPublisher.java
– Web service Client
package com.sri.publish;
import
javax.xml.ws.Endpoint;
import
com.sri.ws.HelloWorldImpl;
public class HelloWorldPublisher{
public static void main(String[] args) {
Endpoint.publish("http://localhost:9090/webservice/helloworld", new HelloWorldImpl());
}
}
Create another package named com.sri.publish and put the
above class in it.
It’s time to access our service. Create a client
HelloWorldClient.java and keep it in the com.sri.client package.
HelloWorldClient.java
– Web Service Client
package com.sri.client;
import
java.net.MalformedURLException;
import java.net.URL;
import javax.xml.namespace.QName;
import
javax.xml.ws.Service;
import
com.sri.ws.HelloWorld;
public class HelloWorldClient {
public static void main(String args[]){
URL url;
try {
url = new URL("http://localhost:9090/webservice/helloworld");
QName qname = new QName("http://ws.sri.com/", "HelloWorldImplService");
Service service = Service.create(url, qname);
HelloWorld hello = service.getPort(HelloWorld.class);
System.out.println(hello.sayHelloToUser("Charles"));
}
catch
(MalformedURLException e) {
e.printStackTrace();
}
}
}
To access the web service WSDL using the following URL.
http://localhost:9090/webservice/helloworld?wsdl
No comments:
Post a Comment