webservice-demo

来源:互联网 发布:php ftp上传大文件 编辑:程序博客网 时间:2024/06/05 07:55

webservice开发步骤:

  服务端开发

—定义服务接口

—实现服务接口

—通过CXF、xfire、axis等框架对外发布服务

 客户端调用

—通过有效途径(双方沟通、UDDI查找等)获取到Webservice的信息

—通过wsdl生成客户端(或者服务提供方提供对应的接口jar包)

—调用服务

 

service接口:

  1. package com.ws.jaxws.sayHello.service;  
  2.  
  3. import javax.jws.WebService;  
  4. import javax.jws.soap.SOAPBinding;  
  5. import javax.jws.soap.SOAPBinding.Style;  
  6.  
  7. @WebService  
  8. //@SOAPBinding(style=Style.RPC)  
  9. public interface SayHelloService {  
  10.     public String sayHello(String name);  
  11. }  

service接口的实现类:

  1. package com.ws.jaxws.sayHello.service.impl;  
  2.  
  3. import javax.jws.WebService;  
  4.  
  5. import com.ws.jaxws.sayHello.service.SayHelloService;  
  6.  
  7. @WebService(endpointInterface = "com.ws.jaxws.sayHello.service.SayHelloService"name = "sayHelloService"targetNamespace = "sayHello")  
  8.  
  9. public class SayHelloServiceImpl implements SayHelloService {  
  10.  
  11.     @Override  
  12.     public String sayHello(String name) {  
  13.         // TODO Auto-generated method stub  
  14.         if("".equals(name)||name==null){  
  15.             name="nobody";  
  16.         }  
  17.         return "hello "+name;  
  18.     }  
  19.  

客户端:

  1. package com.ws.jaxws.sayHello.server;  
  2.  
  3. import javax.xml.ws.Endpoint;  
  4.  
  5. import com.ws.jaxws.sayHello.service.impl.SayHelloServiceImpl;  
  6.  
  7. public class SayHelloServer {  
  8.     public static void main(String[] args) throws Throwable{  
  9.         Endpoint.publish("http://localhost:8888/sayHelloService", new SayHelloServiceImpl());  
  10.         System.out.println("SayHelloService is running....");  
  11.         Thread.sleep(5 * 60 * 1000);  
  12.         System.out.println("time out....");  
  13.         System.exit(0);  
  14.     }  

运行客户端代码后在浏览器输入http://localhost:8888/sayHelloServoce?wsdl,即可生成wsdl代码,如下所示:

wsdl

客户端调用:

  1. package com.ws.jaxws.sayHello.client;  
  2.  
  3. import java.net.MalformedURLException;  
  4. import java.net.URL;  
  5.  
  6. import javax.xml.namespace.QName;  
  7. import javax.xml.ws.Service;  
  8.  
  9. import com.ws.jaxws.sayHello.service.SayHelloService;  
  10.  
  11. public class SayHelloClient {  
  12.     public static void main(String[] args) throws MalformedURLException {  
  13.         String url="http://localhost:8888/sayHelloService?wsdl";  
  14.         Service service=Service.create(new url), new QName("sayHello","SayHelloServiceImplService")); //获得webservice的信息  
  15.         SayHelloService sayHelloService=service.getPort(SayHelloService.class);//return a proxy  
  16.         System.out.println(sayHelloService.sayHello(null));//调用服务  
  17.         System.out.println(sayHelloService.sayHello("zhangsan"));  
  18.     }  

运行客户端代码,控制端输出:
hello nobody
hello zhangsan

0 0