一、首先在http://cxf.apache.org/download.html下载最新版本的CXF
二、写接口文件和接口的实现文件
package webservicePackage;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import javax.xml.ws.BindingType;
@WebService(targetNamespace="http://webservice.api.com/")
@BindingType(javax.xml.ws.soap.SOAPBinding.SOAP12HTTP_BINDING)public interface SCWebServiceI {
@WebMethodpublic
String jsTable(@WebParam(name="companyId")String companyId);
}
2.接口实现类如下,经测试,接口实现类不需要添加@WebService注解,当然添加了也没报错
package webservicePackage;
import javax.jws.WebMethod;
import javax.jws.WebService;
@WebService(targetNamespace="http://webservice.api.com/")
public class SCWebService implements SCWebServiceI {
@WebMethod
public String jsTable(String companyId) {
return companyId;
}
}
三、修改web.xml文件,在末尾增加filter
<servlet>
<servlet-name>CXFServlet</servlet-name>
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CXFServlet</servlet-name>
<url-pattern>/webservice/*</url-pattern>
</servlet-mapping>
四、配置Spring的配置文件,在applicationContext.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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:jaxws="http://cxf.apache.org/jaxws"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
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 implementor="webservicePackage.SCWebService" address="/SCWebService2"/>
</beans>
五、客户端调用
public static void main(String[] args) {
try {
Service sv = new Service();//new 一个服务
Call call = (Call) sv.createCall();//创建一个call对象
call.setTargetEndpointAddress(new URL("http://localhost:8080/PFMMIS/webservice/SCWebService2")); //设置要调用的接口地址以上一篇的为例子
call.setOperationName(new QName("http://webservice.api.com/","jsTable")); //设置要调用的接口方法
call.addParameter("companyId", org.apache.axis.encoding.XMLType.XSD_STRING,javax.xml.rpc.ParameterMode.IN);//设置参数名 id 第二个参数表示String类型,第三个参数表示入参
call.setReturnType(org.apache.axis.encoding.XMLType.XSD_STRING);//返回参数类型
//开始调用方法,假设我传入的参数id的内容是1001 调用之后会根据id返回users信息,以xml格式的字符串返回,也可以json格式主要看对方用什么方式返回
String result = (String) call.invoke(new Object[]{"你好"});
System.out.println(result);//打印字符串
} catch (Exception e) {
e.printStackTrace();
}
}