JAX-WS Web Service Simple Example
November 10, 2013
JAX-WS is java API for XML Web Service. JAX-WS uses XML messages to communicate with the client. These XML messages are Simple Object Access Protocol (SOAP). JAX-WS contains WSDL description of offered services. WSDL is Web Service Description Language. While using SOAP a contract must be established for the services which are being offered. WSDL describes the contract for SOAP based design. We will show a simple example of JAX-WS Web Service. In our example we have created Welcome message Web service that returns welcome message to the client. Follow step by step.
Software Requirement for JAX-WS Demo
The example is using below software.1. JDK 1.6
2. JAX-WS 2.1
3. Eclipse IDE
Create JAX-WS Web Service
Create the class and interface as below.Welcome.java
package com.concretepage.endpoint; import javax.jws.WebMethod; import javax.jws.WebService; @WebService public interface Welcome { @WebMethod public String getWelcomeMsg(String name); }
package com.concretepage.endpoint; import javax.jws.WebService; @WebService(endpointInterface = "com.concretepage.endpoint.Welcome") public class WelcomeImpl implements Welcome { @Override public String getWelcomeMsg(String name){ return "Welcome "+name; } }
Publish JAX-WS Web Service
To publish JAX-WS Web Service, we need to create a publisher class as below.WelcomeMsgPublisher.java
package com.concretepage; import javax.xml.ws.Endpoint; import com.concretepage.endpoint.WelcomeImpl; public class WelcomeMsgPublisher { public static void main(String[] args) { Endpoint.publish("http://localhost:8080/WebServiceDemo/Welcome", new WelcomeImpl()); } }
Eclipse Project Structure for Web Service
Now run the WelcomeMsgPublisher class as java application and access the URL
http://localhost:8080/WebServiceDemo/Welcome?wsdl
You will get XML format data. It means you have successfully published the Web Service. Now you need client to get service.
Create JAX-WS client
To create JAX-WS client we will use a command wsgen . wsgen automatically creates all required java stubs to access the Web Service. To use wsgen, go to command prompt then root directory of Client project. In our case it is WebServiceClient. And run the command aswsimport -s src/main/java http://localhost:8080/WebServiceDemo/Welcome?wsdl
And then create a client class to get service.
WelcomeMsgClient.java
package com.concretepage.client; import com.concretepage.endpoint.Welcome; import com.concretepage.endpoint.WelcomeImplService; public class WelcomeMsgClient { public static void main(String[] args) { WelcomeImplService welService = new WelcomeImplService(); Welcome welcome = welService.getWelcomeImplPort(); System.out.println(welcome.getWelcomeMsg("Everyone!")); } }
Welcome Everyone!