微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

cxf开发并调用webservice

上篇文章xfire的使用中,我都已经介绍过webservice的概念的三个核心内容,并做了它的开发和调用,这里我就用同样的方式,来做一做cxf的。

 

第一步,下载apache-cxf-2.2.3.zip

第二步,新建一个java项目,把解压后cxf的lib下面的jar全都添加到项目的环境里

第三步,编写测试用接口和实现类,代码如下:

 

Java代码 
  1. package test;    
  2.     
  3. import javax.jws.WebService;    
  4. public interface Hello {    
  5.       @WebService  
  6.     public String sayHello(String str);    
  7. }   

class HelloImpl implements Hello {    

  • public String sayHello(String str) {    
  •             
  •         System.out.println("调用成功");    
  •         return "Hello " + str;    
  •     }    
  • }    
  • 第四步,编写服务端的生成代码代码如下:

    import org.apache.cxf.endpoint.Server;    

  • import org.apache.cxf.jaxws.JaxWsServerfactorybean;    
  • class MainServer {    
  •         
  • static void main(String[] args) {    
  •         JaxWsServerfactorybean factory = new JaxWsServerfactorybean();    
  •         factory.setAddress("http://localhost:8080/HelloWebService");    
  •         factory.setServiceClass(HelloImpl.class);    
  •         Server server = factory.create();    
  •         server.start();    
  •    

    第五步,打开浏览器,键入http://localhost:8080/HelloWebService?wsdl   [注:cxf框架中自带jetty6服务器,所以这个例子是可以运行的],wsdl代码如下:

    <?xml version="1.0" encoding="UTF-8" ?>     

  • - <wsdl:deFinitions name="HelloImplService" targetNamespace="http://test/" xmlns:ns1="http://schemas.xmlsoap.org/soap/http" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://test/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:xsd="http://www.w3.org/2001/XMLSchema">    
  • - <wsdl:types>    
  • - <xs:schema elementFormDefault="unqualified" targetNamespace="http://test/" version="1.0" xmlns:tns="http://test/" xmlns:xs="http://www.w3.org/2001/XMLSchema">    
  •   <xs:element name="sayHello" type="tns:sayHello" />     
  •   <xs:element name="sayHelloResponse" type="tns:sayHelloResponse" />     
  • - <xs:complexType name="sayHello">    
  • - <xs:sequence>    
  •   <xs:element minOccurs="0" name="arg0" type="xs:string" />     
  •   </xs:sequence>    
  • 第六步,就是模拟客户端,调用这个wsdl了,新建一个测试类,代码如下:

    import org.apache.cxf.jaxws.JaxWsProxyfactorybean;    

  • class Client {    
  •         JaxWsProxyfactorybean factory = new JaxWsProxyfactorybean();    
  •         factory.setServiceClass(Hello.         Hello hello = (Hello)factory.create();    
  •         System.out.println(hello.sayHello("weberyb"));    
  •  运行后,我们可以在控制台看到下面的结果:

    ....................    

  • 2009-8-13 14:00:42 org.apache.cxf.service.factory.ReflectionServicefactorybean buildServiceFromClass    
  • 信息: Creating Service {http://test/}HelloService from class test.Hello    
  • Hello weberyb    
  •  说明调用成功了。

    这里需要额外提的是,假使你的jdk在1.6或以上的时候,你在导入jar的时候,你得多导入两个,axb-api.jarjaxws-api.jar,不然会报错的。

    版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

    相关推荐