bnhk 发表于 2015-8-1 11:07:37

【转】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代码 http://images.iyunv.com/icon_copy.gif http://images.iyunv.com/icon_star.pnghttp://images.iyunv.com/spinner.gif

[*]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();   
[*]}
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类,实现接口方法





Java代码 http://images.iyunv.com/icon_copy.gif http://images.iyunv.com/icon_star.pnghttp://images.iyunv.com/spinner.gif

[*]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;   
[*]}   
[*]}
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,为用户提供访问入口





Xml代码 http://images.iyunv.com/icon_copy.gif http://images.iyunv.com/icon_star.pnghttp://images.iyunv.com/spinner.gif

[*]
[*]cxf
[*]org.apache.cxf.transport.servlet.CXFServlet
[*]1
[*]
[*]
[*]cxf
[*]/services/*
[*]

cxf
org.apache.cxf.transport.servlet.CXFServlet
1


cxf
/services/*


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





Xml代码 http://images.iyunv.com/icon_copy.gif http://images.iyunv.com/icon_star.pnghttp://images.iyunv.com/spinner.gif

[*]
[*]contextConfigLocation
[*]WEB-INF/beans.xml
[*]
[*]
[*]org.springframework.web.context.ContextLoaderListener
[*]

contextConfigLocation
WEB-INF/beans.xml


org.springframework.web.context.ContextLoaderListener


3.3在WEB-INF下建立beans.xml内容如下





Xml代码 http://images.iyunv.com/icon_copy.gif http://images.iyunv.com/icon_star.pnghttp://images.iyunv.com/spinner.gif

[*]
[*]
[*]
[*]
[*]
[*]
[*]








四、运行项目,检验成果,访问http://localhost:8080/CXFDemo/services/Vote?wsdl
注:CXF与Spring集成的意义
松耦合,通过配置实现WebService的发布
可以通过Spring容器对WebService管理
页: [1]
查看完整版本: 【转】Apache CXF开发WebService