【转】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先建立一个接口
Java代码 复制代码 收藏代码
  1. package com.iflysse.cxf;   
  2. import javax.jws.WebService;   
  3. @WebService  
  4. public interface IVote {   
  5. public boolean vote(String username, int point);   
  6. public int getVoteUserTotal();   
  7. public int getVotePointTotal();   
  8. }  

2.2建立Service类,实现接口方法
Java代码 复制代码 收藏代码
  1. package com.iflysse.cxf;   
  2. import javax.jws.WebService;   
  3. @WebService  
  4. public class Vote implements IVote {   
  5. private static int pointTotal;   
  6. private static int userTotal;   
  7. public int getVotePointTotal() {   
  8. return pointTotal;   
  9. }   
  10. public int getVoteUserTotal() {   
  11. return userTotal;   
  12. }   
  13. public boolean vote(String username, int point) {   
  14. userTotal++;   
  15. pointTotal+=point;   
  16. return true;   
  17. }   
  18. }  

三、在Web.xml中配置CXF,使其生效
3.1在Web.xml中添加CXFServlet,为用户提供访问入口
Xml代码 复制代码 收藏代码
  1. <servlet>  
  2. <servlet-name>cxf</servlet-name>  
  3. <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>  
  4. <load-on-startup>1</load-on-startup>  
  5. </servlet>  
  6. <servlet-mapping>  
  7. <servlet-name>cxf</servlet-name>  
  8. <url-pattern>/services/*</url-pattern>  
  9. </servlet-mapping>  

3.2由于CXF与Spring是天然集成的,所以在Web.xml中添加Spring的配置
Xml代码 复制代码 收藏代码
  1. <context-param>  
  2. <param-name>contextConfigLocation</param-name>  
  3. <param-value>WEB-INF/beans.xml</param-value>  
  4. </context-param>  
  5. <listener>  
  6. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  7. </listener>  

3.3在WEB-INF下建立beans.xml内容如下
Xml代码 复制代码 收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxws="http://cxf.apache.org/jaxws"  
  4. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd    
  5. http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">  
  6. <import resource="classpath:META-INF/cxf/cxf.xml" />  
  7. <import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />  
  8. <import resource="classpath:META-INF/cxf/cxf-servlet.xml" />  
  9. <jaxws:endpoint id="vote" implementor="com.iflysse.cxf.Vote"  
  10. address="/Vote" />  
  11. </beans>  


四、运行项目,检验成果,访问http://localhost:8080/CXFDemo/services/Vote?wsdl

注:CXF与Spring集成的意义
松耦合,通过配置实现WebService的发布
可以通过Spring容器对WebService管理
posted @ 2011-03-21 09:59  blueKnight  Views(1163)  Comments(0Edit  收藏  举报