我个人感觉webservice 过于繁琐,完全可以用http接口的方式取代。但是鉴于有很多公司还在使用它,有时候你要和一些第三方交互时有可能就需要和webservice打交道。那么,还是必要了解一下它的。
首先,这第一篇来看看怎么创建一个webservice。
首先,创建server端。新建一个java工程,名字叫 WebServiceServer
新建一个接口 MyServiceInter
package com.zhutulang.service;
 
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
 
@WebService
public interface MyServiceInter {
 
         @WebResult(name="addResult")
         publicint add(@WebParam(name="a")int a, @WebParam(name="b")intb);
}
  
接口的实现类 MyServiceInterImpl
packagecom.zhutulang.service;
 
importjavax.jws.WebService;
 
@WebService(endpointInterface="com.zhutulang.service.MyServiceInter")
public class MyServiceInterImpl implements MyServiceInter {
 
   @Override
   public int add(int a, int b) {
      System.out.println(a+"+"+b+"="+(a+b));
      return a+b;
   }
 
} 
注意使用的注解。
然后是MyServer
packagecom.zhutulang.service;
 
importjavax.xml.ws.Endpoint;
 
public class MyServer {
 
   public static void main(String[] args) {
      String address = "http://localhost:8888/myservice";
      Endpoint.publish(address, new MyServiceInterImpl());
        System.out.println("publish success!");
   }
} 
将服务发布在http://localhost:8888/myservice
运行后打印出publish success!
在浏览器中输入:http://localhost:8888/myservice?wsdl
出现下图的 xml,则表示已经发布成功。
接下来,我们用wsimport来生成wsdl的客户端代码。打开cmd窗口,输入:
wsimport -d E:\tmp -keep -encoding utf-8-verbose http://localhost:8888/myservice?wsdl
生成的代码保存在E盘的tmp文件夹下。至于wsdl的各个参数,可以自行查看。
然后,我们创建客户端工程,新建一个java工程,名字叫WebServiceClient。将E盘tmp目录下生成的代码拷过去。
在该包下,新建MyClient 类,然后我们就可以这样访问服务了:
packagecom.zhutulang.service;
 
public class MyClient {
 
   public static void main(String[] args) {
         MyServiceInterImplService myService = new MyServiceInterImplService();
         MyServiceInter myServiceInter = myService.getMyServiceInterImplPort();
         System.out.println(myServiceInter.add(12, 55));
   }
} 
 
Wsdl文件的结构:
type: 用来定义访问的类型
message: soap消息
portType : 指定服务接口
operation: 方法名
input: 入参
output: 出参
binding: 指定消息传递所使用的格式
service : 指定服务发布的名称
可以使用tcpmon 来监控webservice的请求。
 
相关的代码下载:http://download.csdn.net/detail/zhutulang/9487929
