JavaRush /Java Blog /Random EN /Web services. Step 2. How to simplify the writing of the ...
eGarmin
Level 41

Web services. Step 2. How to simplify the writing of the client?

Published in the Random EN group
In this quick note, I'd like to return to the web service client code we wrote in the previous step . In this case, I will assume that you have IDEA open, and in it the project from Step 1. In this project, our web service should be running:
package ru.codegym.client;

// нужно, чтобы получить wsdl описание и через него
// дотянуться до самого веб-сервиса
import java.net.URL;
// такой эксепшн возникнет при работе с an objectом URL
import java.net.MalformedURLException;

// классы, чтобы пропарсить xml-ку c wsdl описанием
// и дотянуться до тега service в нем
import javax.xml.namespace.QName;
import javax.xml.ws.Service;

// интерфейс нашего веб-сервиса (нам больше и нужно)
import ru.codegym.ws.HelloWebService;

public class HelloWebServiceClient {
    public static void main(String[] args) throws MalformedURLException {
        // создаем ссылку на wsdl описание
        URL url = new URL("http://localhost:1986/wss/hello?wsdl");

        // Параметры следующего конструктора смотрим в самом первом теге WSDL описания - definitions
        // 1-ый аргумент смотрим в атрибуте targetNamespace
        // 2-ой аргумент смотрим в атрибуте name
        QName qname = new QName("http://ws.codegym.cc/", "HelloWebServiceImplService");

        // Теперь мы можем дотянуться до тега service в wsdl описании,
        Service service = Service.create(url, qname);
        // а далее и до вложенного в него тега port, чтобы
        // получить ссылку на удаленный от нас an object веб-сервиса
        HelloWebService hello = service.getPort(HelloWebService.class);

        // Ура! Теперь можно вызывать удаленный метод
        System.out.println(hello.getHelloString("CodeGym"));
    }
}
Pay attention to how much we need to know in advance. In addition to the fact that you need access to the wsdl description (without this, sorry, nothing):
URL url = new URL("http://localhost:1986/wss/hello?wsdl");
you need to open this xml file yourself and look at the tag definitions, and in it the attributes targetNamespaceand namein order to call the constructor QName:
QName qname = new QName("http://ws.codegym.cc/", "HelloWebServiceImplService");
then you need to manually connect to the tag service:
Service service = Service.create(url, qname);
and in it to the tag port:
HelloWebService hello = service.getPort(HelloWebService.class);
and only after that we can call the remote method:
hello.getHelloString("CodeGym")
The question is: for this, our great-grandfathers died on the battlefield, so that we now do all this manually? And if it's not even our web service, but someone else's. Then this process will be even more unpleasant. The XML format is designed to be read by a machine, not a human. So let's make the machine do the dirty work, and enjoy the process ourselves. For this, we don’t need to do anything special, because. our favorite SDK, which in Java is called the JDK, includes a special wsimport utility . But first things first... First, let's create a new project in IDEA by selecting File > New Project... from the menu and naming the project HelloWS . When we are asked where to open the newly created project, we need to answer New Window, i.e. in a new window, because once again I note that it is very important that the previous project is open, because we remember from Step 1 that we have our web service running in that project. You can, of course, run it simply through the windows console, but I don’t like to do this. From a new project, open the console by selecting View > Tool Windows > Terminal , or simply by pressing Alt+F12 . Now we are at the root of the project, and we need to get into the src folder , so we enter the following command into the console: cd src Now it's time to use the wsimport utility . It works according to the following principle: we pass it a WSDL description, and in response it creates stub files (so-calledStub–classes) that already contain all the functionality we need to access the web service. These classes will be placed in the com.codegym.ws. If you ask where the package name comes from, then I will answer: the package name is the reversed target namespace from the WSDL description. Recall the attribute targetNamespacein the tag definitionsfrom WSDL . There we wrote the following http:// ws.codegym.cc/. And this is not the address of the site, this is how it is customary to describe namespaces in xml, and if we discard http://and expand what remains in the reverse order, we will get our package name. So, let's run the utility: wsimport -keep http://localhost:1986/wss/hello?wsdl For it to work, the path to it must be specified in the PATH environment variable, or you can just use the full path to it. For me it is located in the C:\Program Files\Java\jdk1.8.0_31\bin folder . Please note that all that needs to be done is to transfer the WSDL file via the –keep key , which we have available remotely via the link, unless, of course, we have disabled the web service. What are these stub classes? There are only two of them. One of them isHelloWebService, which is essentially the same web service interface that we manually created in Step 1. The difference is minimal and it lies in the fact that the annotations that we have already met are used a little differently, and in addition, additional annotations are used, which I I don’t know anything, but since everything worked for us without them before, they, obviously, are not mandatory. The second stub class is the HelloWebServiceImplService, which is inherited from the Service. With classServicewe have already encountered in our client. I will not give the code of this class, because I’m hardly ready to explain all his lines, but the essence of the class is that everything that we previously wrote in the client manually to connect to the web service is created automatically in this class and we just need to call one of its methods and we will have everything in openwork. So let's rewrite our client code in a new project using these classes and make sure the code is more concise. To begin with, in the src folder of the new project, create a package com.codegym.client, and in it a class HelloWebServiceClientwith a method main:
package ru.codegym.client;

// подключаем классы-заглушки
import ru.codegym.ws.*;

public class HelloWebServiceClient {
    public static void main(String[] args) {
        // подключаемся к тегу service в wsdl описании
        HelloWebServiceImplService helloService = new HelloWebServiceImplService();
        // получив информацию из тега service подключаемся к самому веб-сервису
        HelloWebService hello = helloService.getHelloWebServiceImplPort();

        // обращаемся к веб-сервису и выводим результат в консоль
        System.out.println( hello.getHelloString("CodeGym Community") );
    }
}
Parsing the code is elementary and what I described in the comments is quite enough. Having launched the client, we should see the line: Hello, CodeGym Community!At the same time, the client from the project from Step 1 will continue to work and display its text that we have written in it, namely Hello, CodeGym! : its purpose has been achieved. We realized that if there is a WSDL description of a web service, then jdk is ready to provide us with automatic generation stubof stub classes to simplify writing a client to this web service. In my opinion, this is a very useful feature in case you want to test someone else's web service and not look into its WSDL description. A look into the future In the next article about web services, I would like to present ideas on how to deploy a web service in a Tomcat servlet container and in different application servers so that you do not need to run the web service as a separate application, as we did in the first 2 Steps. But before that, I think it would be better to make a small digression on the topic of what servlets, servlet containers are and how they differ from application servers and ordinary web s ... . In addition, we will have to make a brief overview of application servers , which, in my opinion, deserve our attention.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION