示例所用工具版本介绍:
CXF:2.7.0 官网:http://cxf.apache.org/index.html
Eclipse:3.5
第一步:新建Web工程,这里命名为CxfDemo(这一步不做介绍了,相信没有不会的)
2.将CXF文件下Lib文件夹中的jar包导入到工程中
3.在工程中新建包com.goma.cxf.test,在包中新建inteface,名称为HelloWord
package com.goma.cxf.test;
import javax.jws.WebMethod;
import javax.jws.WebService;
@WebService
public interface HelloWord {
@WebMethod
// public String sayHello(@WebParam(name="name")String name);
// 通过@WebParam(name="***")来设置WSDL中的参数名称,默认为arg0、arg1……
public String sayHello(String name);
}
4.编写接口实现类HelloWordImpl
package com.goma.cxf.test;
public class HelloWordImpl implements HelloWord {
public String sayHello(String name) {
// TODO Auto-generated method stub
return name.concat(",Hello Word! Yes,Word;don't World!");
}
}
5.发布WebService,采用cxf内置的Jetty服务器发布服务。在HelloWordImpl中添加main()方法,具体如下:
public static void main(String[] args) {
HelloWordImpl implementor = new HelloWordImpl();
JaxWsServerFactoryBean svrFactory = new JaxWsServerFactoryBean();
svrFactory.setServiceClass(HelloWord.class);
//除了http://localhost部分其他部分可以随便写,但格式不能乱 http://IP:PORT/NAME
svrFactory.setAddress("http://localhost:1111/helloWord");
svrFactory.setServiceBean(implementor);
svrFactory.getInInterceptors().add(new LoggingInInterceptor());
svrFactory.getOutInterceptors().add(new LoggingOutInterceptor());
svrFactory.create();
/*************下列方法也可*********
String address="http://localhost:9000/hello";
javax.xml.ws.Endpoint.publish(address, implementor);
System.out.println("WebService run..");
*********/
}
6.在地址栏输入http://localhost:1111/helloWorld?wsdl可以看到自动生成的WSDL
7.访问WebService
方法1:由wsdl可知接口只有一个供调用的operation,方法名称为sayHello,输入参数变量名称为arg0,数据类型为string,采用地址栏URL,输入:http://localhost:1111/helloWorld/sayHello?arg0=goma,显示返回信息如图:
方法2:客户端编码调用,代码如下:
import org.apache.cxf.interceptor.LoggingOutInterceptor;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
public class CxfClient {
public static void main(String[] args) {
// TODO Auto-generated method stub
JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
//factory.getInInterceptors().add(new LoggingInInterceptor());
factory.getOutInterceptors().add(new LoggingOutInterceptor());
factory.setServiceClass(HelloWord.class);
factory.setAddress("http://localhost:1111/helloWorld");
HelloWord client = (HelloWord) factory.create();
String reply = client.sayHello("Goma");
System.out.println("Server said: " + reply);
System.exit(0);
/****下列方法也可
JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
org.apache.cxf.endpoint.Client client = dcf.createClient("http://localhost:1111/helloWorld?wsdl");
//sayHello 为接口中定义的方法名称 张三为传递的参数 返回一个Object数组
Object[] objects=client.invoke("sayHello", "Goma");
//输出调用结果
System.out.println(objects[0].toString());****/
}
}
控制台返回信息如下:
另可参考:http://www.blogjava.net/sxyx2008/archive/2010/09/15/332058.html