---
title: "CXF简单例子"
author: "jxh118"
date: "2008-09-08T10:48:13Z"
tags: []
slug: "cxf"
draft: false
lastmod: "2008-09-08T10:48:13Z"
id: 238448
url: "https://jdh.iteye.com/blog/238448"
---

service框架用apache CXF，服务器tomcat ，还有spring框架  
        OpenSource中关于CXF的简介：Apache CXF一个开源的Service框架，它实现了JCP与Web Service中一些重要标准。CXF简化了构造，集成，面向服务架构(SOA)业务组件与技术的灵活复用。在CXF中，Service使用WSDL标准定义并能够使用各种不同的消息格式(或binding)和网络协议(transports)包括SOAP、XML（通过HTTP或JMS）进行访问。CXF同样支持多种model 如：JAX-WS，JBI，SCA和CORBA service。CXF设计成可灵活部署到各种容器中包括Spring-based，JBI，SCA， Servlet和J2EE容器。

       用CXF构建webservice程序的大致流程如下：

       1 配置web.xml文件，加载CXF

       2 编写java接口，和接口的实现

       3 在spring的applicationContext.xml中配置java文件

       4 创建beans.xml文件，里面配置接口的实现类

      5 运行tomca服务器即可生成wsdl文件

      6 编写测试代码：编写java测试文件和client-beans.xml文件

      7编写运行客户端文件所需的服务器，可以单独编写，也可以在随tomcat启动

示例代码。首先下载cxf，然后解压，将lib下的所有jar包拷到工程下面

    一 最简单的helloword

     1  web.xml

```
<web-app>
    <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>

    <servlet>
        <servlet-name>CXFServlet</servlet-name>
        <display-name>CXF Servlet</display-name>
        <servlet-class>
            org.apache.cxf.transport.servlet.CXFServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>CXFServlet</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>

</web-app>
```

 2  接口HelloWord.java和接口的实现HelloWordImpl.java

```
package com.demo;

import javax.jws.WebService;

/** *//**
* service interface
* 
* @author
* 
*/
@WebService
public interface HelloWord ...{
    String sayHi(String text);
}




package com.demo;

import javax.jws.WebService;

/** *//**
* implementation
* 
* @author 
* 
*/
@WebService
public class HelloWordImpl implements HelloWord ...{

    public String sayHi(String text) ...{
        return "Hi" + text;
    }
}

```

 

3 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="helloWord"
        implementor="com.demo.HelloWordImpl" address="/HelloWord" />

</beans>
```

 

 

4  启动tomcat服务器，在浏览器里面输入[http://localhost:8888/helloword](http://localhost:8888/helloword)后页面上会出现

{[http://demo.com/](http://demo.com/)}HelloWordImplPort ，点击会看到生成的wsdl文件[http://localhost:8888/helloword/HelloWord?wsdl](http://localhost:8888/helloword/HelloWord?wsdl)

5 客户端Client.java和client-beans.xml

```
package com.demo;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public final class Client ...{

    private Client() ...{

    }

    public static void main(String args[]) throws Exception ...{
        // START SNIPPET: client
        ApplicationContext  context = new ClassPathXmlApplicationContext(
                new String[] ...{ "com/demo/client-beans.xml" });

        HelloWord client = (HelloWord) context.getBean("client");

        String response = client.sayHi("+what????");
        System.out.println("Response: " + response);
        System.exit(0);
        // END SNIPPET: client
    }
}
```

```
<?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-2.0.xsd
http://cxf.apache.org/jaxws http://cxf.apache.org/schema/jaxws.xsd">

    <bean id="client" class="com.demo.HelloWord"
        factory-bean="clientFactory" factory-method="create" />

    <bean id="clientFactory"
        class="org.apache.cxf.jaxws.JaxWsProxyFactoryBean">
        <property name="serviceClass" value="com.demo.HelloWord" />
        <property name="address"
            value="http://localhost:9002/HelloWord" />
    </bean>

</beans>

  
```

6 客户端运行时所需的服务器Server.java

```
package com.demo;

import org.mortbay.jetty.Connector;
import org.mortbay.jetty.Handler;
import org.mortbay.jetty.handler.DefaultHandler;
import org.mortbay.jetty.handler.HandlerCollection;
import org.mortbay.jetty.nio.SelectChannelConnector;
import org.mortbay.jetty.webapp.WebAppContext;

public class Server ...{

    protected Server() throws Exception ...{
        System.out.println("Starting Server");

        org.mortbay.jetty.Server server = new org.mortbay.jetty.Server();

        SelectChannelConnector connector = new SelectChannelConnector();
        connector.setPort(9002);
        server.setConnectors(new Connector[] ...{connector});

        WebAppContext webappcontext = new WebAppContext();
        webappcontext.setContextPath("/");

        webappcontext.setWar("WebRoot");

        HandlerCollection handlers = new HandlerCollection();
        handlers.setHandlers(new Handler[] ...{webappcontext, new DefaultHandler()});

        server.setHandler(handlers);
        server.start();
        System.out.println("Server ready...");
        server.join();
    }

    public static void main(String args[]) throws Exception ...{
        new Server();
    }

}
```

 

7 运行客户端Client.java的顺序，先启动tomcat，然后运行Server.java，最后运行Client.java

二 不单独编写Server.java文件，让其和tomcat一同启动.需要改动的地方

1 web.xml

&lt;context-param&gt;  
        &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;  
         &lt;param-value&gt;  
           WEB-INF/applicationContext.xml  
           WEB-INF/beans.xml  
         &lt;/param-value&gt;  
    &lt;/context-param&gt;

    &lt;listener&gt;  
        &lt;listener-class&gt;  
            org.springframework.web.context.ContextLoaderListener  
        &lt;/listener-class&gt;  
    &lt;/listener&gt;

    &lt;servlet&gt;  
        &lt;servlet-name&gt;CXFServlet&lt;/servlet-name&gt;  
        &lt;display-name&gt;CXF Servlet&lt;/display-name&gt;  
        &lt;servlet-class&gt;  
            org.apache.cxf.transport.servlet.CXFServlet  
        &lt;/servlet-class&gt;  
        &lt;load-on-startup&gt;2&lt;/load-on-startup&gt;  
    &lt;/servlet&gt;

    &lt;servlet-mapping&gt;  
        &lt;servlet-name&gt;CXFServlet&lt;/servlet-name&gt;  
        &lt;url-pattern&gt;/webservice/\*&lt;/url-pattern&gt;  
    &lt;/servlet-mapping&gt;  
    

2 applicationContext.xml 配置文件中com.demo.HelloWordFind,  HelloWordFind.java可以写一个查询表HELLO\_WORD中所有内容的代码。相应的HelloWord.java和HelloWordImpl.java也需要修改

&lt;?xml version="1.0" encoding="UTF-8"?&gt;  
&lt;!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "[http://www.springframework.org/dtd/spring-beans.dtd](http://www.springframework.org/dtd/spring-beans.dtd)"&gt;  
&lt;beans default-autowire="byName"&gt;

   &lt;bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"&gt;  
        &lt;property name="locations"&gt;  
            &lt;list&gt;  
                &lt;value&gt;WEB-INF/jdbc.properties&lt;/value&gt;  
            &lt;/list&gt;  
        &lt;/property&gt;  
    &lt;/bean&gt;  
    &lt;bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"&gt;  
        &lt;property name="driverClassName" value="${jdbc.driverClassName}"/&gt;  
        &lt;property name="url" value="${jdbc.url}"/&gt;  
        &lt;property name="username" value="${jdbc.username}"/&gt;  
        &lt;property name="password" value="${jdbc.password}"/&gt;  
    &lt;/bean&gt;  
    &lt;!-- Hibernate SessionFactory --&gt;  
    &lt;bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"&gt;  
        &lt;property name="dataSource" ref="dataSource"/&gt;  
        &lt;property name="mappingResources"&gt;  
            &lt;list&gt;  
                &lt;value&gt;mapping/HelloWord.hbm.xml&lt;/value&gt;  
            &lt;/list&gt;  
        &lt;/property&gt;  
        &lt;property name="hibernateProperties"&gt;  
            &lt;props&gt;  
                &lt;prop key="hibernate.dialect"&gt;org.hibernate.dialect.DB2Dialect&lt;/prop&gt;  
                &lt;prop key="hibernate.show\_sql"&gt;true&lt;/prop&gt;  
            &lt;/props&gt;  
        &lt;/property&gt;  
        &lt;property name="eventListeners"&gt;  
            &lt;map&gt;  
                &lt;entry key="merge"&gt;  
                    &lt;bean class="org.springframework.orm.hibernate3.support.IdTransferringMergeEventListener"/&gt;  
                &lt;/entry&gt;  
            &lt;/map&gt;  
        &lt;/property&gt;  
    &lt;/bean&gt;

    &lt;bean id="hellowordfind" class="com.demo.HelloWordFind"&gt;  
        &lt;property name="sessionFactory" ref="sessionFactory"/&gt;  
        &lt;property name="dataSource" ref="dataSource"/&gt;  
    &lt;/bean&gt;  
&lt;/beans&gt;

3 beans.xml

&lt;?xml version="1.0" encoding="UTF-8"?&gt;

&lt;beans xmlns="[](http://www.springframework.org/schema/beans)[](http://www.springframework.org/schema/beans)[](http://www.springframework.org/schema/beans)[http://www.springframework.org/schema/beans](http://www.springframework.org/schema/beans)"  
    xmlns:xsi="[http://www.w3.org/2001/XMLSchema-instance](http://www.w3.org/2001/XMLSchema-instance)"  
    xmlns:jaxws="[](http://cxf.apache.org/jaxws)[](http://cxf.apache.org/jaxws)[](http://cxf.apache.org/jaxws)[http://cxf.apache.org/jaxws](http://cxf.apache.org/jaxws)"  
    xsi:schemaLocation="  
[](http://www.springframework.org/schema/beans)[](http://www.springframework.org/schema/beans)[http://www.springframework.org/schema/beans](http://www.springframework.org/schema/beans) [](http://www.springframework.org/schema/beans/spring-beans.xsd)[](http://www.springframework.org/schema/beans)[http://www.springframework.org/schema/beans](http://www.springframework.org/schema/beans)/spring-beans.xsd  
[](http://cxf.apache.org/jaxws)[](http://cxf.apache.org/jaxws)[http://cxf.apache.org/jaxws](http://cxf.apache.org/jaxws) [http://cxf.apache.org/schemas/jaxws.xsd](http://cxf.apache.org/schemas/jaxws.xsd)"&gt;

    &lt;import resource="classpath:META-INF/cxf/cxf.xml" /&gt;  
    &lt;import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" /&gt;  
    &lt;import resource="classpath:META-INF/cxf/cxf-servlet.xml" /&gt;  
    &lt;bean id="hellowordimpl" class="com.demo.HelloWordImpl"&gt;  
      &lt;property name="sessionFactory" ref="sessionFactory"/&gt;  
      &lt;property name="dataSource" ref="dataSource"/&gt;  
      &lt;property name="hellowordfind" ref="hellowordfind" /&gt;      
    &lt;/bean&gt;  
    &lt;jaxws:endpoint id="helloword"  implementor="#hellowordimpl" address="/hellword" /&gt;  
&lt;/beans&gt;

4 主要需要改动的已经完成。客户端代码变化不大。