您的位置:首页 > 其它

CXF发布webservice的一个小demo

2011-07-26 11:17 351 查看
CXF是apache出的新一代的XFire系列的框架。它对spring的结合更好,配置起来更简单。这个demo用一个与上面不一样的方法来发布webservice。这次用一个POJO注释的方法来发布service。通过这个文章和上一篇文章大家可以看到发布的两种方法。首先我们先定义一个interface,在这个接口上的注释就是用此把这个接口做为webservice发布的对象import javax.jws.WebService;@WebService
public interface HelloWorld {
String sayHi(String text);
} 然后再定义一个接口的实现,这里注释定义了EDI和service。 import javax.jws.WebService;@WebService(endpointInterface = "org.suzsoft.cxf.HelloWorld", serviceName = "HelloWorld")
public class HelloWorldImpl implements HelloWorld {

@Override
public String sayHi(String text) {
// TODO Auto-generated method stub
return "Hi "+text;
}
} 然后我们接下来就要做个关于CXF的定义了,这里要写一个server的方法,来定义cxf的地址以及实现和cxf服务器的启动和关闭。 import javax.xml.ws.Endpoint;public class Server { protected Server() throws Exception {
// START SNIPPET: publish
System.out.println("Starting Server");
HelloWorldImpl implementor = new HelloWorldImpl();
String address = "http://localhost:9000/helloWorld";
Endpoint.publish(address, implementor);
// END SNIPPET: publish
} public static void main(String args[]) throws Exception {
new Server();
System.out.println("Server ready..."); Thread.sleep(5 * 60 * 1000);
System.out.println("Server exiting");
System.exit(0);
}
} 在这个时候我们就可以运行server方法,接着我们就可以在http://localhost:9000/helloWorld?wsdl下看到wsdl文件了。下面我们就可以定义客户端调用service了 import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import javax.xml.ws.soap.SOAPBinding;import org.suzsoft.cxf.HelloWorld;
public final class Client { private static final QName SERVICE_NAME
= new QName("http://org.suzsoft.cxf/", "HelloWorld");
private static final QName PORT_NAME
= new QName("http://org.suzsoft.cxf/", "HelloWorldPort");
private Client() {
} public static void main(String args[]) throws Exception {
Service service = Service.create(SERVICE_NAME);
// Endpoint Address
String endpointAddress = "http://localhost:9000/helloWorld"; // Add a port to the Service
service.addPort(PORT_NAME, SOAPBinding.SOAP11HTTP_BINDING, endpointAddress);

HelloWorld hw = service.getPort(HelloWorld.class);
System.out.println(hw.sayHi("Ares")); }} 这样一个简单的cxf的helloworld就可以完成了,大家可以用这个作为一个简单的参考来用cxf发布webservice。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: