Java WebService 是一种基于SOAP(Simple Object Access Protocol)协议的远程调用技术,它允许不同的应用程序在网络上通过XML消息进行通信。
以下是使用Java WebService的基本步骤:
package com.example;
import javax.jws.WebMethod;
import javax.jws.WebService;
@WebService
public interface HelloWorld {
@WebMethod
String sayHello(String name);
}
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 + "!";
}
}
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);
}
}
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和创建客户端来实现远程调用。