温馨提示×

Java-WebService基础使用

小云
95
2023-09-23 08:48:53
栏目: 编程语言

Java WebService 是一种基于SOAP(Simple Object Access Protocol)协议的远程调用技术,它允许不同的应用程序在网络上通过XML消息进行通信。

以下是使用Java WebService的基本步骤:

  1. 定义一个接口:首先需要定义一个接口,其中包含需要对外提供的方法。
package com.example;
import javax.jws.WebMethod;
import javax.jws.WebService;
@WebService
public interface HelloWorld {
@WebMethod
String sayHello(String name);
}
  1. 实现接口:实现刚刚定义的接口,提供具体的方法实现。
package com.example;
import javax.jws.WebService;
@WebService(endpointInterface = "com.example.HelloWorld")
public class HelloWorldImpl implements HelloWorld {
@Override
public String sayHello(String name) {
return "Hello " + name + "!";
}
}
  1. 发布WebService:使用JavaSE提供的Endpoint类来发布WebService。
package com.example;
import javax.xml.ws.Endpoint;
public class HelloWorldPublisher {
public static void main(String[] args) {
String url = "http://localhost:8080/hello";
Endpoint.publish(url, new HelloWorldImpl());
System.out.println("WebService已发布,访问地址为:" + url);
}
}
  1. 创建客户端:在客户端中使用Java提供的JAX-WS库来调用WebService。
package com.example;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import java.net.URL;
public class HelloWorldClient {
public static void main(String[] args) throws Exception {
URL url = new URL("http://localhost:8080/hello?wsdl");
QName qname = new QName("http://example.com/", "HelloWorldImplService");
Service service = Service.create(url, qname);
HelloWorld hello = service.getPort(HelloWorld.class);
String result = hello.sayHello("World");
System.out.println(result);
}
}

以上就是使用Java WebService的基本步骤,通过定义接口、实现接口、发布WebService和创建客户端来实现远程调用。

0