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管理