学习新东西要养成写博客的习惯:
一、新建web工程CXFDemo,作为服务端,如下所示:
IHelloService.java 接口:
import javax.jws.WebService;
/**
* <p>
* WebService接口
* </p>
*
* @author IceWee
* @date 2012-7-6
* @version 1.0
*/
@WebService
public interface IHelloService {
public String sayHello(String username);
}
HelloServiceImpl 实现:
/**
* <p>
* WebService实现类
* </p>
*
* @author IceWee
* @date 2012-7-6
* @version 1.0
*/
@WebService(endpointInterface = "bing.server.IHelloService", serviceName = "HelloService")
public class HelloServiceImpl implements IHelloService {
@Override
public String sayHello(String username) {
System.out.println(username);
return "hello, " + username;
}
}
applicationContext-server.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jaxws="http://cxf.apache.org/jaxws"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">
<!--
***注意***
手动添加的内容:
xmlns:jaxws="http://cxf.apache.org/jaxws"
http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd"
-->
<import resource="classpath:META-INF/cxf/cxf.xml" />
<import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />
<import resource="classpath:META-INF/cxf/cxf-servlet.xml" />
<jaxws:endpoint id="helloService" implementor="bing.server.HelloServiceImpl" address="/helloService" />
</beans>
到此servcie端就已经写好了。
下面是client端的内容,有两种方式访问:
public class HelloServiceClient {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(
"applicationContext-client.xml");
IHelloService helloService = (IHelloService) context.getBean("client");
String response = helloService.sayHello("Peter");
System.out.println(response);
}
}
如果把client端的代码和service端写在一起,如上图可以访问了,如果client的代码是另外一个独立的工程就要把service的代码打成jar包,引入到client工程里。
小结:这种调用service的好处在于调用过程非常简单,就几行代码就完成一个webservice的调用,但是客户端也必须依赖服务器端的接口,这种调用方式限制是很大的,要求服务器端的webservice必须是java实现--这样也就失去了使用webservice的意义
二、使用JaxWsDynamicClientFactory类,只要指定服务器端wsdl文件的位置,然后指定要调用的方法和方法的参数即可@Test
public void client2() throws Exception {
JaxWsDynamicClientFactory clientFactory = JaxWsDynamicClientFactory
.newInstance();
Client client = clientFactory
.createClient("http://localhost:8080/CXFDemo/ws/helloService?wsdl");
Object[] result = client.invoke("sayHello", "Sqs");
System.out.println(result[0]);
}