1.编写要发布成webservice的类:
package test.jws.service;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
@WebService(targetNamespace = "http://jdk.study.pengch.org/client") //这句是指定客户端获取服务端服务后存放的类路径。注意是反着的
@SOAPBinding(style = SOAPBinding.Style.RPC)
public class HelloWorld {
@WebMethod
public String sayHello(String name) {
return "hello:" + name;
}
}
2.发布服务:
package test.jws.service;
import javax.xml.ws.Endpoint;
public class StartService {
public static void main(String[] args) {
Endpoint.publish("http://localhost:8080/HelloService", new HelloWorld());
//http://localhost:8080/HelloService是指发布的地址
}
}
3.运行:
运行StartService ,开发浏览器输入:http://localhost:8080/HelloService?wsdl
就能看到内容.
4.生成客户端类:
进入到源文件所在目录: wsimport -keep http://localhost:8080/HelloService?wsdl
会自动生成一些代码。
-keep : keep generated files
wsimport -p com -keep http://localhost:8080/HelloService?wsdl
将生成的类放在com包中. -p :指定目标包名.
5.编写客户端测试类:
package org.pengch.study.jdk.client;
public class TestClient {
public static void main(String[] args) {
HelloWorldService service = new HelloWorldService();
HelloWorld _hello = service.getHelloWorldPort();
System.out.println(_hello.sayHello("test"));
}
}
注意:必须先将服务端类StartService启动后, 客户类才能正常运行.