webservciescxf框架之客戶端與服務端實例詳解
本文參考了:http://www.webxml.com.cn/zh_cn/index.aspx
可以關注我之前發的文章,那是采用jdk發布服務並且使用wsimpor來生成客戶端的。
但本文采用的是soap1.2協議,而wsimport僅對soap1.1協議有效,所以,本文采用的是
cxf框架提供的wsdl2java 來生成客戶端,如下:
wsdl2java -d . http://127.0.0.1/framework?wsdl
另外,需要強調的是wsdl2java工具(axis好像也提供了)既支持soap1.1協議,也支持soap1.2協議,生成客戶端代碼。
如圖:
此外,soap1.1與soap1.2的區別
1)命名空間不一樣
soap1.1:xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
soap1.2:xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
2) 請求類型不一樣
soap1.2 :Content-Type: application/soap+xml; charset=utf-8
soap1.1:Content-Type: text/xml; charset=utf-8
1)服務端cxfservices:
package com.neusoft.si;
import javax.jws.WebService; import javax.xml.ws.BindingType;
@WebService @BindingType(value=javax.xml.ws.soap.SOAPBinding.SOAP12HTTP_BINDING)
public class cxfservices {
public String sayHello(String name){ return "hello:"+name;
}
}
2) 發布服務端server
package com.neusoft.si;
import org.apache.cxf.interceptor.LoggingInInterceptor;
import org.apache.cxf.interceptor.LoggingOutInterceptor;
import org.apache.cxf.jaxws.JaxWsServerFactoryBean;
public class mycxfserver {
public static void main(String[] args) {
//soap1.1---wsimpot可以使用
//soap1.1 , soap1.2---wsdl2java -d . wsdl路徑
JaxWsServerFactoryBean server=new JaxWsServerFactoryBean();
//客戶端調用時,打印輸入輸出日志
server.getInInterceptors().add(new LoggingInInterceptor());
server.getOutInterceptors().add(new LoggingOutInterceptor());
server.setAddress("http://127.0.0.1/framework");
server.setServiceClass(cxfservices.class);
server.setServiceBean(new cxfservices());
server.create();
System.out.println("server ready");
}
}
3)客戶端:
客戶端生成代碼根據wsdl2java生成下,此處不做展示。
package com.slrc;
import com.neusoft.si.Cxfservices;
import com.neusoft.si.CxfservicesService;
public class cxf_client {
public static void main(String[] args) {
CxfservicesService service=new CxfservicesService();
Cxfservices client=service.getCxfservicesPort();
String result=client.sayHello("jwe");
System.out.println(result);
}
}
發布帶有接口的cxf服務類時需要特別注意的是@WebService注釋是加在接口上的,此外,
server.setServiceClass(cxfserviceInterface.class); ----此處應為接口類
server.setServiceBean(new cxfservicesImpl()); ---此處應為接口實現類