JavaRush /Java Blog /Random EN /Web services. Step 1. What is a web service and how to wo...
eGarmin
Level 41

Web services. Step 1. What is a web service and how to work with it?

Published in the Random EN group
The topic title is really a question, because... I myself don’t know what it is and for the first time I will try to work with it within the framework of this article. The only thing I can guarantee is that the code presented below will work, but my phrases will only be assumptions and guesses about how I myself understand all this. So, let's go... Web services.  Step 1. What is a web service and how to work with it?  - 1

Introduction

We need to start with why the concept of web services was created. By the time this concept appeared in the world, technologies already existed that allowed applications to interact at a distance, where one program could call some method in another program, which could be launched on a computer located in another city or even country. All this is abbreviated as RPC (Remote Procedure Calling). Examples include CORBA technologies, and for Java - RMI (Remote Method Invoking). And everything seems to be good in them, especially in CORBA, because... You can work with it in any programming language, but something was still missing. I believe that the disadvantage of CORBA is that it works through some of its own network protocols instead of simple HTTP, which will fit through any firewall. The idea of ​​the web service was to create an RPC that would be inserted into HTTP packets. Thus began the development of the standard. What are the basic concepts of this standard:
  1. SOAP . Before calling a remote procedure, you need to describe this call in an XML file in SOAP format. SOAP is simply one of the many XML markups that are used in web services. Everything we want to send somewhere via HTTP is first converted into an XML SOAP description, then stuffed into an HTTP packet and sent to another computer on the network via TCP/IP.
  2. WSDL . There is a web service, i.e. a program whose methods can be called remotely. But the standard requires that this program be accompanied by a description that says that “yes, you’re right - this is really a web service and you can call such and such methods from it.” This description is represented by another XML file, which has a different format, namely WSDL. Those. WSDL is just an XML file describing a web service and nothing more.
Why so briefly you ask? Can't you be more specific? It’s probably possible, but to do this you’ll have to turn to books such as T. Mashnin, “Java Web Services.” There, over the first 200 pages, there is a detailed description of each tag of the SOAP and WSDL standards. Is it worth doing? In my opinion, no, because... all this is created automatically in Java, and you only need to write the contents of the methods that are supposed to be called remotely. So, an API such as JAX-RPC appeared in Java. If anyone doesn't know, when they say that Java has such and such an API, it means that there is a package with a set of classes that encapsulate the technology in question. JAX-RPC evolved over time from version to version and eventually became JAX-WS. WS obviously stands for WebService and you might think that this is simply a renaming of RPC as a popular buzzword these days. This is not true, because Now web services have moved away from the original idea and allow you not only to call remote methods, but also to simply send document messages in SOAP format. I don’t know why this is needed yet; it’s unlikely that the answer here will be “just in case it’s needed.” I myself would like to learn from more experienced comrades. And lastly, then JAX-RS appeared for so-called RESTful web services, but this is the topic of a separate article. The introduction can end here, because... Next we will learn to work with JAX-WS.

General approach

In web services there is always a client and a server. The server is our web service and is sometimes called the endpoint (as in, the end point where SOAP messages from the client reach). We need to do the following:
  1. Describe the interface of our web service
  2. Implement this interface
  3. Launch our web service
  4. Write a client and remotely call the desired web service method
You can launch a web service in different ways: either describe a class with a method mainand launch the web service directly as a server, or deploy it to a server like Tomcat or any other. In the second case, we ourselves do not launch a new server and do not open another port on the computer, but simply tell the Tomcat servlet container that “we have written web service classes here, please publish them so that everyone who contacts you can use our use the web service." Regardless of the method of launching the web service, we will have the same client.

Server

Let's launch IDEA and create a new project Create New Project . Specify the name HelloWebService and click the Next button , then the Finish button . In the src folder we will create the package ru.javarush.ws . In this package we will create an interface HelloWebService:
package ru.javarush.ws;

// это аннотации, т.е. способ отметить наши классы и методы,
// How связанные с веб-сервисной технологией
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;

// говорим, что наш интерфейс будет работать How веб-сервис
@WebService
// говорим, что веб-сервис будет использоваться для вызова методов
@SOAPBinding(style = SOAPBinding.Style.RPC)
public interface HelloWebService {
    // говорим, что этот метод можно вызывать удаленно
    @WebMethod
    public String getHelloString(String name);
}
In this code, the classes are so-called annotations WebServiceand WebMethoddo nothing except mark our interface and its method as a web service. The same applies to the class SOAPBinding. The only difference is that SOAPBindingit is an annotation with parameters. In this case, a parameter is used stylewith a value indicating that the web service will work not through document messages, but as a classic RPC, i.e. to call a method. Let's implement our interface logic and create a class in our package HelloWebServiceImpl. By the way, I note that ending a class with Impl is a convention in Java, according to which the implementation of interfaces is so designated (Impl - from the word implementation, i.e. implementation). This is not a requirement and you are free to name the class whatever you want, but good manners require it:
package ru.javarush.ws;

// таже annotation, что и при описании интерфейса,
import javax.jws.WebService;

// но здесь используется с параметром endpointInterface,
// указывающим полное Name класса интерфейса нашего веб-сервиса
@WebService(endpointInterface = "ru.javarush.ws.HelloWebService")
public class HelloWebServiceImpl implements HelloWebService {
    @Override
    public String getHelloString(String name) {
        // просто возвращаем приветствие
        return "Hello, " + name + "!";
    }
}
Let's launch our web service as an independent server, i.e. without the participation of any Tomcat and application servers (this is a topic for a separate discussion). To do this, in the project structure in the src folder, we will create a package ru.javarush.endpoint, and in it we will create a class HelloWebServicePublisherwith a method main:
package ru.javarush.endpoint;

// класс, для запуска веб-serverа с веб-сервисами
import javax.xml.ws.Endpoint;
// класс нашего веб-сервиса
import ru.javarush.ws.HelloWebServiceImpl;

public class HelloWebServicePublisher {
    public static void main(String... args) {
        // запускаем веб-server на порту 1986
        // и по addressу, указанному в первом аргументе,
        // запускаем веб-сервис, передаваемый во втором аргументе
        Endpoint.publish("http://localhost:1986/wss/hello", new HelloWebServiceImpl());
    }
}
Now let's run this class by pressing Shift+F10 . Nothing will appear in the console, but the server is running. You can verify this by typing the line http://localhost:1986/wss/hello?wsdl in your browser . The page that opens, on the one hand, proves that we have a web server (http://) running on port 1986 on our computer (localhost), and, on the other hand, shows a WSDL description of our web service. If you stop the application, the description will become unavailable, as will the web service itself, so we won’t do this, but move on to writing the client.

Client

In the project folder src we will create a package ru.javarush.client, and in it a class HelloWebServiceClientwith a method main:
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"));
    }
}
I gave maximum comments on the code in the listing. I have nothing to add, so let’s run (Shift+F10). We should see the text in the console: Hello, JavaRush!If you didn’t see it, then you probably forgot to start the web service.

Conclusion

This topic provided a brief excursion into web services. Once again, I will say that much of what I wrote is my guess as to how it works, and therefore you should not trust me too much. I would be grateful if knowledgeable people correct me, because then I will learn something. UPD. Let's continue the conversation
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION