上篇文章xfire的使用中,我都已经介绍过webservice的概念的三个核心内容,并做了它的开发和调用,这里我就用同样的方式,来做一做cxf的。
?
第一步,下载apache-cxf-2.2.3.zip
第二步,新建一个java项目,把解压后cxf的lib下面的jar全都添加到项目的环境里
第三步,编写测试用接口和实现类,代码如下:
?
- package?test;????
- ????
- import?javax.jws.WebService;????
- public?interface?Hello?{????
- ??????@WebService??
- ????public?String?sayHello(String?str);????
- }???
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:??
Hello?weberyb????
?说明调用成功了。
这里需要额外提的是,假使你的jdk在1.6或以上的时候,你在导入jar的时候,你得多导入两个,axb-api.jar和jaxws-api.jar,不然会报错的。
(编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|