JavaRush /Java Blog /Random EN /Web services. Step 2. How to simplify writing a client?
eGarmin
Level 41

Web services. Step 2. How to simplify writing a client?

Published in the Random EN group
On this quick note, I'd like to revisit 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. Our web service should be launched in this project:
package ru.javarush.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.javarush.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.javarush.ru/", "HelloWebServiceImplService");

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

        // Ура! Теперь можно вызывать удаленный метод
        System.out.println(hello.getHelloString("JavaRush"));
    }
}
Notice how much we need to know in advance. In addition to the fact that you need access to the wsdl description (without this, sorry, there is no way):
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 nameto call the constructor QName:
QName qname = new QName("http://ws.javarush.ru/", "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("JavaRush")
The question is: is this why our great-grandfathers died on the battlefields, so that we now do it all by hand? 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 machines, not humans. So let's let the machine do the dirty work and enjoy the process. For this, we don’t need to do anything special, because... Our favorite SDK, called JDK in Java, includes a special utility called wsimport . But first things first... First, let's create a new project in IDEA by selecting File > New Project... from the menu and giving the project the name 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 I’ll note once again 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, simply launch it through the Windows console, but I don’t like doing that. From the new project, open the console by selecting View > Tool Windows > Terminal , or simply pressing Alt+F12 . Now we are in 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 on the following principle: we pass it a WSDL description, and in response it creates stub files (so-called Stub-classes), which already contain all the functionality we need to access the web service. These classes will be placed in the package ru.javarush.ws. If you ask where the package name comes from, the answer is: the package name is the reversed target namespace from the WSDL description. Remember the attribute targetNamespacein the tag definitionsfrom the WSDL . There we had the following written http:// ws.javarush.ru/. And this is not the site address, this is how it is customary to describe namespaces in xml, and if we discard http://and expand what remains in 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 simply use the full path to it. For me it is located in the folder C:\Program Files\Java\jdk1.8.0_31\bin . Please note that all you need to do is pass the WSDL file via the –keep key , which is available remotely via a 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 created manually in Step 1. The difference is minimal and it lies in the fact that the annotations that we have already encountered are used slightly differently, and in addition, additional annotations are used, which I mentioned I don’t know anything, but since everything worked for us without them before, then they are obviously not mandatory. The second class is stub HelloWebServiceImplService, which inherits from the class Service. We have already encountered the class Servicein our client. I will not give the code of this class, because... I’m hardly ready to explain all of its lines, but the essence of the class comes down to the fact 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’ll have everything in openwork. So let's rewrite our client's code in a new project using these classes and make sure the code is more concise. First, in the src folder of the new project, let's create a package ru.javarush.client, and in it a class HelloWebServiceClientwith a method main:
package ru.javarush.client;

// подключаем классы-заглушки
import ru.javarush.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("JavaRush 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, JavaRush Community!At the same time, the client from the project from Step 1 will continue to work and display its text that we wrote in it, namely: Hello, JavaRush! At this point, perhaps, we can finish this Step, because his goal 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 for this web service. In my opinion, this is a very useful feature when you want to test someone else’s web service and not peek into its WSDL description. A look into the future In the next article about web services, I would like to outline ideas on how to deploy a web service into a Tomcat servlet container and into 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 short digression on the topic of what servlets, servlet containers are and how they differ from application servers and regular web... . 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