接口:
在接口中添加WebService的注解,将其标注为WebService的服务接口。
@WebService public interface Hello { public String sayHello(String str); }
实现类:
1 public class HelloImpl implements Hello { 2 3 public String sayHello(String str) { 4 System.out.println("调用成功"); 5 return "Hello " + str; 6 } 7 }
WebService服务器端:
1 public class MainServer { 2 public static void main(String[] args) { 3 JaxWsServerFactoryBean factory = new JaxWsServerFactoryBean(); 4 factory.setAddress("http://localhost:8080/HelloWebService"); 5 factory.setServiceClass(HelloImpl.class); 6 Server server = factory.create(); 7 server.start(); 8 } 9 }
factory.setAddress("http://localhost:8080/HelloWebService");
设置服务在服务器上部署的位置
factory.setServiceClass(HelloImpl.class);
设置服务暴露的接口实现类
完成之后运行MainServer中的main方法。
注:因为CXF框架中有Jetty 6 服务器,所以这个的demo发布在其中运行。
之后打开浏览器,输入:
http://localhost:8080/HelloWebService?wsdl
正常打开有wsdl显示则成功
编写客户端:
public class Client { public static void main(String[] args) { JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean(); factory.setServiceClass(Hello.class); factory.setAddress("http://localhost:8080/HelloWebService"); Hello hello = (Hello)factory.create(); System.out.println(hello.sayHello("weberyb")); } }
factory.setServiceClass(Hello.class);
设置访问服务器端的指定接口。
factory.setAddress("http://localhost:8080/HelloWebService");
设置访问的服务的地址。
factory.create()
创建代理对象以供远程调用
之后运行Client中main方法,可以在控制台的服务器端看见如下输出:
- ....................
- 2009-8-13 14:00:42 org.apache.cxf.service.factory.ReflectionServiceFactoryBean buildServiceFromClass
- 信息: Creating Service {http://test/}HelloService from class test.Hello
- Hello weberyb
说明客户端调用WebService成功。
至此,这个简单的WebService开发完毕