1.编写提供服务的类 package cn.xt.wsdl;import java.util.Date;import javax.jws.WebMethod;import javax.jws.WebParam;import javax.jws.WebResult;import javax.jws.WebService;import javax.xml.ws.Endpoint;@WebService(serviceName="MyService"
1.编写提供服务的类
package cn.xt.wsdl;
import java.util.Date;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.xml.ws.Endpoint;
@WebService(serviceName="MyService",name="MyService",targetNamespace="http://client.wsdl.xt.cn")
public class MyService {
public static void main(String[] args) {
MyService gt = new MyService();
Endpoint.publish("http://127.0.0.1:8899/test", gt);
}
@WebMethod(operationName="sayGood")
@WebResult(name="ResultMsg")
public String sayHi(@WebParam(name="userName")String name){
return "hi..."+name+" at "+new Date().toLocaleString();
}
public void sayHello(){
System.out.println("hello..."+new Date().toLocaleString());
}
}
webservice提供了如下注解来决定客户端生成的代码,可以达到避免暴露服务端真实包结构、方法名、返回值的目的
MyService 必须提供一个非静态方法作为业务方法,否则会抛出以下异常
Exception in thread "main" com.sun.xml.internal.ws.model.RuntimeModelerException: The web service defined by the class cn.xt.wsdl.MyService does not contain any valid WebMethods. at com.sun.xml.internal.ws.model.RuntimeModeler.buildRuntimeModel(RuntimeModeler.java:232) at com.sun.xml.internal.ws.server.EndpointFactory.createSEIModel(EndpointFactory.java:328) at com.sun.xml.internal.ws.server.EndpointFactory.createEndpoint(EndpointFactory.java:190) at com.sun.xml.internal.ws.api.server.WSEndpoint.create(WSEndpoint.java:498) at com.sun.xml.internal.ws.transport.http.server.EndpointImpl.createEndpoint(EndpointImpl.java:246) at com.sun.xml.internal.ws.transport.http.server.EndpointImpl.publish(EndpointImpl.java:170) at com.sun.xml.internal.ws.spi.ProviderImpl.createAndPublishEndpoint(ProviderImpl.java:118) at javax.xml.ws.Endpoint.publish(Endpoint.java:240) at cn.xt.wsdl.MyService.main(MyService.java:13)
执行上面代码,访问地址:http://127.0.0.1:8899/test?wsdl,显示如下界面代表发布成功:
其中service标签的name属性代表发布服务的名称,与port标签的name属性中的值一起决定客户端调用时生成的实体类
2.将编写的服务导出供客户端调用
打开命令行窗口,输入wsimport -s . http://127.0.0.1:8899/test?wsdl 在当前目录生成客户端代码
-d 代表生成class文件,-s代表生成java文件
将生成的目录拷贝到工程结构下
3.调用服务
调用的方式有2种:
1.直接根据生成的源码调用
public static void main(String[] args) {
MyService service = new MyService_Service().getMyServicePort();
String print = service.sayGood("hah");
System.out.println(print);
}
public static void main(String[] args) throws Exception {
URL url = new URL("http://127.0.0.1:8899/test");
QName qname = new QName("http://client.wsdl.xt.cn","MyService");
QName portName = new QName("http://client.wsdl.xt.cn","MyServicePort");
Service service = Service.create(url, qname);
MyService gretting = service.getPort(portName , MyService.class);
gretting.sayHello();
}
当只剩MyService.java文件时,会遇到这一行报错,删除即可
@XmlSeeAlso({ ObjectFactory.class })
