CXF做爲java領域主流的WebService實現框架,Java程序員有必要掌握它。java
CXF主頁:http://cxf.apache.org/程序員
簡介:百度百科web
今天的話,主要是用CXF來開發下WebService服務器端接口,明天寫下開發客戶端接口;apache
這裏用Maven。瀏覽器
首先建一個Maven的j2se項目;服務器
項目的jre用1.8,由於1.8有webservice的默認實現。不要用1.5 否則下面你用個人代碼會有問題,用1.5的話,還須要另外加jar包,這裏爲了你們省事,要換成1.8;框架
根據規範,咱們先建一個接口類:HelloWorldfrontend
package com.wishwzp.webservice; import javax.jws.WebService; @WebService public interface HelloWorld { public String say(String str); }
再建一個具體的實現類:HelloWorldImplurl
package com.wishwzp.webservice.impl; import javax.jws.WebService; import com.wishwzp.webservice.HelloWorld; @WebService public class HelloWorldImpl implements HelloWorld{ public String say(String str) { return "hello" + str; } }
最後建一個發佈服務的主類:Serverspa
package com.wishwzp.webservice; import javax.xml.ws.Endpoint; import com.wishwzp.webservice.impl.HelloWorldImpl; public class Server { public static void main(String[] args) { System.out.println("web service start"); HelloWorld implementor = new HelloWorldImpl(); String address = "http://192.168.0.110/helloWorld"; Endpoint.publish(address, implementor); // JDK實現 暴露webservice接口 System.out.println("web service started"); } }
這裏的Endpoint是Jdk自身實現的WebService。因此到這裏咱們不須要用到CXF的任何東西。
這裏的address,寫上本身的本機IP
咱們運行下Server類:
運行效果以下:
咱們在瀏覽器裏訪問:http://192.168.0.110/helloWorld?wsdl
效果:
說明已經成功調用了webservice接口;
這裏的wsdl 是 Web Services Description Language的縮寫,是一個用來描述Web服務和說明如何與Web服務通訊的XML語言。WSDL是Web Service的描述語言,用於描述Web Service的服務,接口綁定等,爲用戶提供詳細的接口說明書。
請求後獲得的是一個xml規範文檔。是一套規範,後面會具體介紹,任何語言平臺技術均可以解析。
下面咱們介紹使用CXF來實現webservice接口:
咱們先在pom.xml中加入:
<dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-core</artifactId> <version>3.1.5</version> </dependency> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-frontend-jaxws</artifactId> <version>3.1.5</version> </dependency> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-transports-http-jetty</artifactId> <version>3.1.5</version> </dependency>
這裏要額外加入jetty,做爲webservice發佈的服務器。jetty是一個內嵌的web服務器;
咱們把Server改下。換成CXF實現:
package com.wishwzp.webservice; import javax.xml.ws.Endpoint; import org.apache.cxf.jaxws.JaxWsServerFactoryBean; import com.wishwzp.webservice.impl.HelloWorldImpl; public class Server { public static void main(String[] args) { System.out.println("web service start"); HelloWorld implementor = new HelloWorldImpl(); String address = "http://192.168.0.110/helloWorld"; //Endpoint.publish(address, implementor); // JDK實現 暴露webservice接口 JaxWsServerFactoryBean factoryBean = new JaxWsServerFactoryBean(); factoryBean.setAddress(address); // 設置暴露地址 factoryBean.setServiceClass(HelloWorld.class); // 接口類 factoryBean.setServiceBean(implementor); // 設置實現類 factoryBean.create(); System.out.println("web service started"); System.out.println("web service started"); } }
運行效果和剛纔同樣,這裏就再也不重複;