Exemple JAX-WS Hello World - Style RPC

JAX-WS est fourni avec JDK 1.6, ce qui facilite le développement de services Web Java. Ce tutoriel vous montre comment effectuer les tâches suivantes:

  1. Créez un point de terminaison de service Web de style RPC basé sur SOAP à l’aide de JAX-WS.

  2. Créez un client de service Web Java manuellement.

  3. Créez un client de service Web Java via l’outil wsimport .

  4. Créez un client de service Web Ruby.

Vous serez surpris de voir à quel point il est simple de développer un service Web de style RPC dans JAX-WS.

Point de terminaison du service Web JAX-WS

Les étapes suivantes montrent comment utiliser JAX-WS pour créer un point de terminaison de service Web de style RPC.

1. Créer une interface de noeud final de service Web

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. Créer une implémentation de noeud final de service Web

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. Créer un éditeur de noeud final

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());
    }

}

Exécutez l’éditeur de terminal et votre « hello world web service » est déployé dans l’URL « http://localhost : 9999/ws/hello ».

4. Testez-le

Vous pouvez tester le service Web déployé en accédant au document WSDL (Web Service Definition Language) généré via cette URL « http://localhost : 9999/ws/hello? Wsdl ».

Clients de service Web

Ok, le service Web est correctement déployé. Voyons maintenant comment créer un client de service Web pour accéder au service publié.

1. Client de service Web Java

Sans outil, vous pouvez créer un client de service Web Java comme suit:

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"));

    }

}

Sortie

Hello World JAX-WS mkyong

2. Client de service Web Java via l’outil wsimport

Vous pouvez également utiliser l’outil « wsimport » pour analyser le fichier wsdl publié et générer les fichiers client nécessaires (stub) pour accéder au service Web publié.

  • Où est wsimport? Cet outil wsimport ** est fourni avec le JDK, vous pouvez le trouver dans le dossier « JDK PATH/bin__».

Émettez la commande “ wsimport ”.

wsimport -keep http://localhost:9999/ws/hello?wsdl

Il générera les fichiers client nécessaires, ce qui dépend du fichier wsdl fourni. Dans ce cas, il générera une interface et un fichier de mise en œuvre de service.

Fichier: Hello World.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);
    }

}

Créez maintenant un client de service Web Java qui dépend des fichiers générés ci-dessus.

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"));

    }

}

Voici la sortie

Hello World JAX-WS mkyong

3. Client de service Web Ruby

Souvent, le développement de services Web est un usage mixte avec d’autres langages de programmation. Voici donc un exemple de client de service Web Ruby, utilisé pour accéder au service JAX-WS publié.

# 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}"

Sortie

getHelloWorldAsString : Hello World JAX-WS mkyong

Traçage du trafic SOAP

De haut en bas, montrant comment l’enveloppe SOAP circule entre le client et le serveur. Voir à nouveau le client de service Web:

    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"));
  • Remarque ** Pour surveiller le trafic SOAP, rien de plus simple, reportez-vous à ce guide: "lien://services Web/jax-ws/comment-suivre-soap-message-in-eclipse-ide/[Comment suivre le message SOAP dans Eclipse IDE]“.

1. Demander un fichier WSDL

Tout d’abord, le client envoie une demande wsdl au point de terminaison du service, voir le trafic HTTP ci-dessous:

  • Demande d’envoi du client: **

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
  • Réponse d’envoi du serveur: **

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 ()

Un second appel, une demande d’appel de méthode de vente du client dans une enveloppe SOAP, et l’envoyer au point de terminaison du service. Au niveau du noeud final de service, appelez la méthode demandée, insérez le résultat dans une enveloppe SOAP et renvoyez-la au client.

  • Demande d’envoi du client: **

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>
  • Réponse d’envoi du serveur: **

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>

Fait, tous les commentaires sont appréciés.

Télécharger le code source

Téléchargez-le - lien://wp-content/uploads/2010/11/JAX-WS-HelloWorld-RPC-Example.zip[JAX-WS-HelloWorld-RPC-Example.zip](14 Ko)

lien://tag/hello-world/[hello world]lien://tag/jax-ws/[jax-ws]lien://tag/web-services/[services web]