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和創建客戶端來實現遠程調用。