4/08/2016

JAX-WS hello world examble using annotations in java

XML Web Services (JAX-WS) API is readily available in java to create web-service easily.This web-service is completely based on the annotations.We may need to work with java versions more than 5 because of the annotation dependency. Lets see the hello world web-service application. First we need to create an end point interface and this interface contains what are methods we are going to expose as a service.


package com;

import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;

@WebService
@SOAPBinding(style = Style.RPC)
public interface HelloWorld {

 @WebMethod
 String getMessage(String name);

}

There are three important annotations used here i. @Webservice: It marks this Java class as one implementing a Web service. ii. @WebMethod: This annotation signifies this particular method is going to expose as a webservice operation. This method should be public and this must return a value iii. @SoapBinding: This annotation signifies the mapping of the Web Service onto the SOAP message protocol. Now end point interface is ready and lets create the end point implementation.

package com;

import javax.jws.WebService;

//Service Implementation
@WebService(endpointInterface = "com.HelloWorld")
public class HelloWorldImpl implements HelloWorld {

 @Override
 public String getMessage(String name) {
  return "Success "+name;
 }

}

In the web service annotation we need to specify the package location of the Endpoint interface. Now we are done with the webservice implementation, in order to access the webservice we need to publish it as like below.

package com;

import javax.xml.ws.Endpoint;

//Endpoint publisher
public class Publisher {

 public static void main(String[] args) {
  Endpoint.publish("http://localhost:8500/ws/hello", new HelloWorldImpl());
  System.out.println("Published");
 }

}

Webservice is ready to use now,JRE internally creating wsdl files for our implementation this can be verified by accessing the URL http://localhost:8500/ws/hello?wsdl

CommentsComments