WebService

1.简介

WebService是用于设备或者程序之间用于通信的服务

Web Service可以通过以下方式定义:

  • 是客户端服务器应用程序或应用程序组件进行通信
  • 网络上两个设备之间的通信方法。
  • 是一个可互操作的机器到机器通信的软件系统。
  • 是用于在两个设备或应用程序之间交换信息的标准或协议的集合。
参考:https://www.yiibai.com/web_service/what-is-web-service.html

从上图看到,如果是不同语言的程序之间通信就是通过WebService来实现的

2.Java WebService分类

JAX-WS:SOAP Web服务

JAX-RS:RESTful Web服务

 3.JAX-WS示例

JAX-WS又分为RPS和文档服务

1.服务端应用程序

(1)创建一个接口

package test;

import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;

@WebService
@SOAPBinding(style = SOAPBinding.Style.DOCUMENT)
public interface Function {
    @WebMethod
    public String tranWords(String words);
}

文档或者RPS只要在注解上声明即可

(2)实现类方法

package test;

import javax.jws.WebService;
import javax.xml.ws.Endpoint;

@WebService(endpointInterface = "test.Function")
public class FunctionImpl implements Function{
    @Override
    public String tranWords(String words) {
        String res="";
        for(char ch:words.toCharArray()){
            res+=ch+",";
        }
        return res;
    }

    public static void main(String[] args) {
        Endpoint.publish("http://localhost:8089/service/function",new FunctionImpl());
        System.out.println("Publish Success");
    }
}

运行main方法后,输入http://localhost:8089/service/function?wsdl的地址就可看到生成的wsdl文件

 2.客户端代码

package test;

import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import java.net.MalformedURLException;
import java.net.URL;

public class TestClient {
    public static void main(String[] args) throws MalformedURLException {
        URL url=new URL("http://localhost:8089/service/function?wsdl");

        QName qname=new QName("http://test/","FunctionImplService");
        Service service=Service.create(url,qname);
        Function function=service.getPort(Function.class);
        System.out.println(function.tranWords("ILOVEYOU"));
    }
}

运行得到:

原文地址:https://www.cnblogs.com/wutongshu-master/p/11805543.html