使用CXF实现一个WebService
简单的一个CXF例子
服务器端:
1.烤jar包 所需jar包如下 在cxf 的lib下找
2.建一个java project
new 一个 interface
package org.howie.service;
import javax.jws.WebService;
@WebService //注解
public interface Hello {
public String sayHi(String name);
}
3.实现该interface
import javax.jws.WebService;
import org.howie.service.Hello;
//serviceName定义了WEBSERVICE服务的名称,客户端通过HelloWS 的getxxzzxxxport方法来获得该接口
@WebService(endpointInterface="org.howie.service.Hello",serviceName="HelloWS")
public class HelloImpl implements Hello{
@Override
public String sayHi(String name) {
System.out.println("111hi:"+name);
return "2222hi:"+name;
}
}
4.暴露服务
package org.howie.main;
import javax.xml.ws.Endpoint;
import org.howie.service.Hello;
import org.howie.service.impl.HelloImpl;
public class MainTest {
public static void main(String[] args) {
String url="http://192.168.1.102:9090/helloService";
Hello hello=new HelloImpl();
//通过Endpoint的静态方法暴露webService 传入2个参数 该service的url,和服务接口
Endpoint.publish(url, hello);
}
}
5.测试 服务端
用浏览器 登陆 http://192.168.1.102:9090/helloService?wsdl
如果见到一堆xml,那就成功了
客户端:
1.配置环境变量
将 apache-cxf-2.4.0\bin 的路径配置到path中
2.获取服务端代码
建一个项目 cxf_client 定义一个action(暂且为空)
如果是window系统 cmd 进入到客户端的项目中 cd cd cd 。。。到 cxf_client 下的org 下
输入 wsdl2java http://192.168.1.102:9090/helloService?wsdl 并执行
如果没报错,那就成功了,回到eclipse 刷新一下。会看到有一个新的包。
3.调用webservice
public class UserAction {
public static void main(String[] args) {
HelloWS helloWS=new HelloWS(); //这就是客户端定义的serviceName 这是一个工程类
Hello hello=helloWS.getHelloImplPort(); //通过getXXXPort() 获取服务类
String str=hello.sayHi("howie"); 调用服务类方法.
System.out.println(str);
}
}