Skip to main content

JAX-WS Hello World Example – RPC Style


JAX-WS Hello World Example – RPC Style



AX-WS is bundled with JDK 1.6, which makes Java web service development easier to develop. This tutorial shows you how to do the following tasks:
  1. Create a SOAP-based RPC style web service endpoint by using JAX-WS.
  2. Create a Java web service client manually.
  3. Create a Java web service client via wsimport tool.
  4. Create a Ruby web service client.
You will be surprise of how simple it is to develop a RPC style web service in JAX-WS.
Note
In general words, “web service endpoint” is a service which published outside for user to access; where “web service client” is the party who access the published service.

JAX-WS Web Service End Point

The following steps showing how to use JAX-WS to create a RPC style web service endpoint.

1. Create a Web Service Endpoint Interface

File : HelloWorld.java
package com.mkyong.ws;
 
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;
 
//Service Endpoint Interface
@WebService
@SOAPBinding(style = Style.RPC)
public interface HelloWorld{
 
 @WebMethod String getHelloWorldAsString(String name);
 
}

2. Create a Web Service Endpoint Implementation

File : HelloWorldImpl.java
package com.mkyong.ws;
 
import javax.jws.WebService;
 
//Service Implementation
@WebService(endpointInterface = "com.mkyong.ws.HelloWorld")
public class HelloWorldImpl implements HelloWorld{
 
 @Override
 public String getHelloWorldAsString(String name) {
  return "Hello World JAX-WS " + name;
 }
 
}

3. Create a Endpoint Publisher

File : HelloWorldPublisher.java
package com.mkyong.endpoint;
 
import javax.xml.ws.Endpoint;
import com.mkyong.ws.HelloWorldImpl;
 
//Endpoint publisher
public class HelloWorldPublisher{
 
 public static void main(String[] args) {
    Endpoint.publish("http://localhost:9999/ws/hello", new HelloWorldImpl());
    }
 
}
Run the endpoint publisher, and your “hello world web service” is deployed in URL “http://localhost:9999/ws/hello“.

4. Test It

You can test the deployed web service by accessing the generated WSDL (Web Service Definition Language) document via this URL “http://localhost:9999/ws/hello?wsdl” .

Web Service Clients

Ok, web service is deployed properly, now let’s see how to create web service client to access to the published service.

1. Java Web Service Client

Without tool, you can create a Java web service client like this :
package com.mkyong.client;
 
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import com.mkyong.ws.HelloWorld;
 
public class HelloWorldClient{
 
 public static void main(String[] args) throws Exception {
 
 URL url = new URL("http://localhost:9999/ws/hello?wsdl");
 
        //1st argument service URI, refer to wsdl document above
 //2nd argument is service name, refer to wsdl document above
        QName qname = new QName("http://ws.mkyong.com/", "HelloWorldImplService");
 
        Service service = Service.create(url, qname);
 
        HelloWorld hello = service.getPort(HelloWorld.class);
 
        System.out.println(hello.getHelloWorldAsString("mkyong"));
 
    }
 
}
Output
Hello World JAX-WS mkyong

2. Java Web Service Client via wsimport tool

Alternative, you can use “wsimport” tool to parse the published wsdl file, and generate necessary client files (stub) to access the published web service.
Where is wsimport? This wsimport tool is bundle with the JDK, you can find it at “JDK_PATH/bin” folder.
Issue “wsimport” command.
wsimport -keep http://localhost:9999/ws/hello?wsdl
It will generate necessary client files, which is depends on the provided wsdl file. In this case, it will generate one interface and one service implementation file.
File : HelloWorld.java
package com.mkyong.ws;
 
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
 
/**
 * This class was generated by the JAX-WS RI.
 * JAX-WS RI 2.1.1 in JDK 6
 * Generated source version: 2.1
 * 
 */
@WebService(name = "HelloWorld", targetNamespace = "http://ws.mkyong.com/")
@SOAPBinding(style = SOAPBinding.Style.RPC)
public interface HelloWorld {
 
    /**
     * 
     * @param arg0
     * @return
     *     returns java.lang.String
     */
    @WebMethod
    @WebResult(partName = "return")
    public String getHelloWorldAsString(
        @WebParam(name = "arg0", partName = "arg0")
        String arg0);
 
}
File : HelloWorldImplService.java
package com.mkyong.ws;
 
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import javax.xml.ws.WebEndpoint;
import javax.xml.ws.WebServiceClient;
import javax.xml.ws.WebServiceFeature;
 
/**
 * This class was generated by the JAX-WS RI.
 * JAX-WS RI 2.1.1 in JDK 6
 * Generated source version: 2.1
 * 
 */
@WebServiceClient(name = "HelloWorldImplService", 
 targetNamespace = "http://ws.mkyong.com/", 
 wsdlLocation = "http://localhost:9999/ws/hello?wsdl")
public class HelloWorldImplService
    extends Service
{
 
    private final static URL HELLOWORLDIMPLSERVICE_WSDL_LOCATION;
 
    static {
        URL url = null;
        try {
            url = new URL("http://localhost:9999/ws/hello?wsdl");
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        HELLOWORLDIMPLSERVICE_WSDL_LOCATION = url;
    }
 
    public HelloWorldImplService(URL wsdlLocation, QName serviceName) {
        super(wsdlLocation, serviceName);
    }
 
    public HelloWorldImplService() {
        super(HELLOWORLDIMPLSERVICE_WSDL_LOCATION, 
   new QName("http://ws.mkyong.com/", "HelloWorldImplService"));
    }
 
    /**
     * 
     * @return
     *     returns HelloWorld
     */
    @WebEndpoint(name = "HelloWorldImplPort")
    public HelloWorld getHelloWorldImplPort() {
        return (HelloWorld)super.getPort(
   new QName("http://ws.mkyong.com/", "HelloWorldImplPort"), 
   HelloWorld.class);
    }
 
    /**
     * 
     * @param features
     *  A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy.  
     *  Supported features not in the <code>features</code> parameter will have their default values.
     * @return
     *  returns HelloWorld
     */
    @WebEndpoint(name = "HelloWorldImplPort")
    public HelloWorld getHelloWorldImplPort(WebServiceFeature... features) {
        return (HelloWorld)super.getPort(
   new QName("http://ws.mkyong.com/", "HelloWorldImplPort"), 
   HelloWorld.class, 
   features);
    }
 
}
Now, create a Java web service client which depends on the above generated files.
package com.mkyong.client;
 
import com.mkyong.ws.HelloWorld;
import com.mkyong.ws.HelloWorldImplService;
 
public class HelloWorldClient{
 
 public static void main(String[] args) {
 
  HelloWorldImplService helloService = new HelloWorldImplService();
  HelloWorld hello = helloService.getHelloWorldImplPort();
 
  System.out.println(hello.getHelloWorldAsString("mkyong"));
 
    }
 
}
Here’s the output
Hello World JAX-WS mkyong

3. Ruby Web Service Client

Often time, web service development is mixed use with other programming language. So, here’s a Ruby web service client example, which is used to access the published JAX-WS service.
# package for SOAP-based services
require 'soap/wsdlDriver'
 
wsdl_url = 'http://localhost:9999/ws/hello?wsdl'
 
service = SOAP::WSDLDriverFactory.new(wsdl_url).create_rpc_driver
 
# Invoke service operations.
data1 = service.getHelloWorldAsString('mkyong')
 
# Output results.
puts "getHelloWorldAsString : #{data1}"
Output
getHelloWorldAsString : Hello World JAX-WS mkyong

Tracing SOAP Traffic

From top to bottom, showing how SOAP envelope flows between client and server. See #1 web service client again :
    URL url = new URL("http://localhost:9999/ws/hello?wsdl");
    QName qname = new QName("http://ws.mkyong.com/", "HelloWorldImplService");
    Service service = Service.create(url, qname);
 
    HelloWorld hello = service.getPort(HelloWorld.class);
 
    System.out.println(hello.getHelloWorldAsString("mkyong"));
Note To monitor SOAP traffic is very easy, see this guide – “How to trace SOAP message in Eclipse IDE“.

1. Request a WSDL file

First, client send a wsdl request to service endpoint, see HTTP traffic below :
Client send request :
GET /ws/hello?wsdl HTTP/1.1
User-Agent: Java/1.6.0_13
Host: localhost:9999
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Connection: keep-alive
Server send response :
HTTP/1.1 200 OK
Transfer-encoding: chunked
Content-type: text/xml;charset=utf-8
 
<?xml version="1.0" encoding="UTF-8"?>
 
<definitions 
 xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" 
 xmlns:tns="http://ws.mkyong.com/" 
 xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
 xmlns="http://schemas.xmlsoap.org/wsdl/" 
 targetNamespace="http://ws.mkyong.com/" 
 name="HelloWorldImplService">
 
 <types></types>
 
<message name="getHelloWorldAsString">
 <part name="arg0" type="xsd:string"></part>
</message>
<message name="getHelloWorldAsStringResponse">
 <part name="return" type="xsd:string"></part>
</message>
 
<portType name="HelloWorld">
 <operation name="getHelloWorldAsString" parameterOrder="arg0">
  <input message="tns:getHelloWorldAsString"></input>
  <output message="tns:getHelloWorldAsStringResponse"></output>
 </operation>
</portType>
 
<binding name="HelloWorldImplPortBinding" type="tns:HelloWorld">
 
 <soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="rpc"></soap:binding>
 <operation name="getHelloWorldAsString">
  <soap:operation soapAction=""></soap:operation>
  <input>
   <soap:body use="literal" namespace="http://ws.mkyong.com/"></soap:body>
  </input>
  <output>
   <soap:body use="literal" namespace="http://ws.mkyong.com/"></soap:body>
  </output>
 </operation>
 
</binding>
 
<service name="HelloWorldImplService">
<port name="HelloWorldImplPort" binding="tns:HelloWorldImplPortBinding">
<soap:address location="http://localhost:9999/ws/hello"></soap:address>
</port>
</service>
</definitions>

2. hello.getHelloWorldAsString()

A second call, client put method invoke request in SOAP envelope and send it to service endpoint. At the service endpoint, call the requested method and put the result in a SOAP envelope and send it back to client.
Client send request :
POST /ws/hello HTTP/1.1
SOAPAction: ""
Accept: text/xml, multipart/related, text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Content-Type: text/xml; charset=utf-8
User-Agent: Java/1.6.0_13
Host: localhost:9999
Connection: keep-alive
Content-Length: 224
 
<?xml version="1.0" ?>
 <S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
  <S:Body>
   <ns2:getHelloWorldAsString xmlns:ns2="http://ws.mkyong.com/">
    <arg0>mkyong</arg0>
   </ns2:getHelloWorldAsString>
  </S:Body>
 </S:Envelope>
Server send response :
HTTP/1.1 200 OK
Transfer-encoding: chunked
Content-type: text/xml; charset=utf-8
 
<?xml version="1.0" ?>
 <S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
  <S:Body>
   <ns2:getHelloWorldAsStringResponse xmlns:ns2="http://ws.mkyong.com/">
    <return>Hello World JAX-WS mkyong</return>
   </ns2:getHelloWorldAsStringResponse>
  </S:Body>
 </S:Envelope>

Download Source Code

Download It – JAX-WS-HelloWorld-RPC-Example.zip (14KB)
Tags : 

Popular posts from this blog

ORA-02051 Another Session Or Branch In Same Transaction Failed

ORA-02051 Another Session Or Branch In Same Transaction Failed (Doc ID 2253226.1)          SYMPTOMS for ORA-02051 Another Session Or Branch In Same Transaction Failed. Database performance is slow and caused   the transactions ORA-02051 another session or branch in same transaction failed or finalized CAUSE for ORA-02051 Another Session Or Branch In Same Transaction Failed. Session transactions branches caused the issue Excessive Waits On The Event "Global transaction acquire instance locks" SOLUTION Please use below sql and identified underscore parameter values for ORA-02051 Another Session Or Branch In Same Transaction Failed : SQL> select a.ksppinm "Parameter", b.ksppstvl "Session Value",c.ksppstvl "Instance Value"  FROM x$ksppi a,x$ksppcv b, x$ksppsv c  WHERE a.indx = b.indx AND a.indx = c.indx AND a.ksppinm LIKE '/_%' escape '/'  AND (a.ksppinm like '%clusterwide_global%' or a.ksppinm like '%disable_autotune_...

Video Conferencing Project in Java Source Code

Video Conferencing Project in Java Source Code     ################################################################################# FEATURE ################################################################################# 1.Multi Chat(Used Threadpole) 2.P2P Chat 3.P2P Audio Chat 4.P2P Video Chat 5.Complete Automated 6.H.263 compression Video 7.raw audio PREREQUISITE: 1. JUST INSTALL jmf-2.1.1 e @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ *****/  just need to copy the client side code and run it to a pc   not need any manual IP ***/  How to run : Just run server side code in a PC and then Run Client side code to different  PC.Then the work is done. Server Side Code: ClientListener.java Clients.java Main.java MessageListener.java ServerConstant.java ServerManager.java ServerMonitor.java ServerStatusListener.java   ClientListener.java /*  * To change this template, choose Tools | Templates  * and open the tem...

DBA_SCHEDULER_JOB_RUN_DETAILS and PURGE_LOG

How to purge DBA_SCHEDULER_JOB_RUN_DETAILS? Manually deleting from DBA_SCHEDULER_JOB_RUN_DETAILS is not recommended by oracle.DBA_SCHEDULER_JOB_RUN_DETAILS is a view that is using two master tables (scheduler$_job_run_details and scheduler$_event_log) and display the information about jobs history. As there is one procedure named PURGE_LOG and Oracle have Scheduler for this procedure. It will purges all rows in the job log that are older than 30 days.This is the default behavior of this procedure. You can change this to any number of days you want by setting the attribute "SET_SCHEDULER_ATTRIBUTE". e.g. exec DBMS_SCHEDULER.SET_SCHEDULER_ATTRIBUTE('log_history','15'); It will purge all logs older than 15days and it will maintain the history of 15days. But If you want manually purge these logs, you can use below solution:- exec DBMS_SCHEDULER.PURGE_LOG(log_history => 15, which_log => 'JOB_LOG'); It will purge all entries from the jog log that are o...

Oracle character AL32UTF8

The character set determines what languages can be represented in the database. Oracle recommends using Unicode (AL32UTF8) as the database character set. AL32UTF8 is Oracle's name for the UTF-8 encoding of the Unicode standard. The Unicode standard is the universal character set that supports most of the currently spoken languages of the world. The use of the Unicode standard is indispensable for any multilingual technology, including database processing. Changing the database character set is a time consuming and complex project. Therefore, it is very important to select the right character set at installation time. If the language is American English or a Western European language, then the default character set is WE8MSWIN1252. Each Microsoft Windows ANSI Code Page can store data from only one language or a limited group of languages, such as only Western European, or only Eastern European, or only Japanese. AL32UTF8 is a multibyte character set, database operations on character...

ORA-02291: integrity constraint violated - parent key not found

“Error: ORA-02291: integrity constraint violated - parent key not found” Reason:    A Primary key does not have the same value as the foreign key. We will discuss it in detail later in this article. Action:   For  ORA-02291: integrity constraint violated - parent key not found  You may either delete the foreign key or the matching primary key can be added. In either way, you may try to get this error corrected. Let's understand more about ORA-02291: integrity constraint violated - parent key not found? The Oracle software brought us the strength by which multiple tables in the database can pass on information so efficiently. Not only this, there are numerous devices in this software which enables access to and sourcing data from multiple tables. You can easily execute complicated database issues without an unusual uncertainty by creating statements with the fantastic characteristic of this software. Realistically, if we talk about user or database no one is perf...