Apache CXF開發WebService

Apache CXF是一種新型的WebService框架,使用它開發WebService將會極大的提高開發效率。CXF與Spring的集成是非常自然的,如果你不知道Spring請問Google。
CXF項目主頁:http://cxf.apache.org
由於CXF集成了很多主流的工具包,所以它的體積非常大,30M+,有興趣的研究下哪些包是非必須的,煩請告知。
費話少說,開工。
一、在Eclipse中建立一個Dynamic Web project,添加CXF/lib下所有jar到項目的lib中
二、編寫Service類
2.1先建立一個接口

package com.iflysse.cxf;
import javax.jws.WebService;
@WebService
public interface IVote {
public boolean vote(String username, int point);
public int getVoteUserTotal();
public int getVotePointTotal();
}

2.2建立Service類,實現接口方法

package com.iflysse.cxf;
import javax.jws.WebService;
@WebService
public class Vote implements IVote {
private static int pointTotal;
private static int userTotal;
public int getVotePointTotal() {
return pointTotal;
}
public int getVoteUserTotal() {
return userTotal;
}
public boolean vote(String username, int point) {
userTotal++;
pointTotal+=point;
return true;
}
}

三、在Web.xml中配置CXF,使其生效
3.1在Web.xml中添加CXFServlet,爲用戶提供訪問入口

<servlet>
<servlet-name>cxf</servlet-name>
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>cxf</servlet-name>
<url-pattern>/services/*</url-pattern>
</servlet-mapping>

3.2由於CXF與Spring是天然集成的,所以在Web.xml中添加Spring的配置

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>WEB-INF/beans.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

3.3在WEB-INF下建立beans.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">
<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="vote" implementor="com.iflysse.cxf.Vote"
address="/Vote" />
</beans>


四、運行項目,檢驗成果,訪問http://localhost:8080/CXFDemo/services/Vote?wsdl

注:CXF與Spring集成的意義
鬆耦合,通過配置實現WebService的發佈
可以通過Spring容器對WebService管理
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章