You are on page 1of 4

Creating a simple Web Services and Client with JAX-WS

1. 2. 3. 4. 5. 6. 7. 8. 9. Code the implementation class. Compile the implementation class. Use wsgen to generate the artifacts required to deploy the service. Package the files into a WAR file. Deploy the WAR file. The web service artifacts (which are used to communicate with clients) are generated by the Application Server during deployment. Code the client class. Use wsimport to generate and compile the web service artifacts needed to connect to the service. Compile the client class. Run the client. Coding the Service Endpoint Interface

package com.sample.first.jaxws; import javax.jws.WebMethod; import javax.jws.WebService; @WebService public interface HelloWorld {

@WebMethod public String sayHello(String name); }

Coding the Service Endpoint Implementation Class

package com.sample.first.jaxws; import javax.jws.WebService; @WebService (endpointInterface = "com.sample.first.jaxws.HelloWorld") public class HelloWorldImpl implements HelloWorld {

private String message = new String("Hello"); //default public constructor public void HelloWorldImpl(){} @Override public String sayHello(String name){ return message+" "+name; } }

Coding the Endpoint Publisher Class


package com.sample.first.jaxws; import javax.xml.ws.Endpoint; public class HelloWorldPublisher { public static void main(String[] args) { Endpoint.publish("http://localhost:8080/SampleJAXWS/Hello", new HelloWorld()); } }

Run the above Publisher class as a normal Java application. This class publishes the Web Service on the defined URL (http://localhost:8080/SampleJAXWS/Hello)

Testing the published Web Service Open any internet browser and type the Endpoint URL in the address bar by appending ?WSDL at the end http://localhost:8080/SampleJAXWS/Hello?WSDL If there is no error, the WSDL should be displayed.

Testing the Web Service with a client class


package com.sample.first.jaxws.client import java.net.MalformedURLException; import java.net.URL; import javax.xml.namespace.QName; import javax.xml.ws.Service; import com.sample.first.jaxws.HelloWorld; public class HelloWorldClient { public static void main(String[] args) throws MalformedURLException { URL url = new URL("http://localhost:8080/SampleJAXWS/Hello?wsdl"); QName qname = new QName("http://jaxws.first.sample.com/", "HelloWorldImplService"); Service service = Service.create(url, qname); HelloWorld hello = service.getPort(HelloWorld.class); System.out.println(hello.sayHello(World")); } } Running the Web Service client

Run the Web Service client class as a normal Java application. The output would be as below: Hello World

Other ways of testing a Web Service A Web Service running on a specified endpoint can be tested using clients like Web Services Explorer (that comes along with Eclipse) SOAP UI JMeter etc.

You might also like