一:首先搭建服务端
01:首先在pom.xml文件引入需要的jar包
02:在web.xml文件下面引入配置文件
因为cxf的spring容器必须使用ContextLoadListener来启动,如果是spring mvc还要引入ContextLoaderListener
03:在web.xml文件下引入spring-cxf.xml文件,我的配置文件如下,所以不用再另外加配置内容
04:在存放配置文件的地方引入配置文件spring-cxf.xml文件内容如下
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">
address="/HelloWordService" />
05:服务端的接口HelloWordService
import javax.jws.WebService;
@WebService
public interface HelloWordService {
String sayHello(String text);
}
服务端接口的实现类HelloWordServiceImpl
import javax.jws.WebService;
@WebService(endpointInterface="com.phhc.webservice.HelloWordService",serviceName="HelloWordService")
public class HelloWordServiceImpl implements HelloWordService{
@Override
public String sayHello(String text) {
System.out.println(text);
return "Hello "+text;
}
}
06:至此服务端搭建完成,启动项目,在浏览器地址下输入地址http://127.0.0.1:8080/mavendemo/webservice/HelloWordService?wsdl
出现如下如表示成功
注:Could not load Webservice SEI
这是因为在实现类的endpointInterface的路径写错了
No service was found.
1:首先检查路径的地址名称,在spring-cxf.xml是否存在
2:原因是因为cxf的spring容器必须使用ContextLoadListener来启动,而spring MVC采用的DispatcherServlet来启动的,所以无法加载cxf的服务。
参考文章解决http://kyfxbl.iteye.com/blog/1432920
2:创建客户端访问。
01:下载apache cxf的包,如apache-cxf-3.1.6 下载路径为cxf.apache.org/download.html
02:解压apache-cxf-3.1.6到某一目录下,我是解压到了D:\apache-cxf-3.1.6\apache-cxf-3.1.6下面
03:打开dos命令界面切换到cxf解压到的路径的bin路径下
04:在命令行中输入wsdl2java -p com... -d D:\\src -client http://api.xxx.cn/xxxAPI/service/auditResBatchQueryService?wsdl
-p 指定其wsdl的命名空间,也就是要生成代码的包名:
-d 指定要产生代码所在目录
-client 生成客户端测试web service的代码
05:客户端代码调用
public static void main(String[] args) {
JaxWsProxyFactoryBean factorBean = new JaxWsProxyFactoryBean();
factorBean.setServiceClass(HelloWordService.class);
factorBean.setAddress("http://127.0.0.1:8080/Demo/webservice/HelloWordService?wsdl");
HelloWordService impl = (HelloWordService) factorBean.create();
System.out.println(impl.sayHello("aaaaaaaa"));
}
正常执行main方法,执行成功。
如果出现以下异常信息:请使用 @XmlType.name 和 @XmlType.namespace 为类分配不同的名称
如图:
这是HelloWordService 接口中classname地址写的不正确,这个地址是命令-p的时候的地址,如果-p命令地址写错,就会出现以上异常信息,解决办法,可以手动
修改(如果修改地方比较少的话),建议重新生成客户端代码。