GVKun编程网logo

cxf webservice(cxf webservice开发)

27

对于想了解cxfwebservice的读者,本文将是一篇不可错过的文章,我们将详细介绍cxfwebservice开发,并且为您提供关于(webservice+cxf+mybatis+mysql+spr

对于想了解cxf webservice的读者,本文将是一篇不可错过的文章,我们将详细介绍cxf webservice开发,并且为您提供关于(webservice+cxf+mybatis+mysql+springmvc) webservice + cxf 能够跑起来的cxf ,来这里,,、CXF Webservice 6 - Spring 3 整合Apache CXF WebService、CXF WebService 7 - Spring整合CXF,发布RSETful 风格WebService、CXF介绍及用 cxf 做的 webservice 简单例子的有价值信息。

本文目录一览:

cxf webservice(cxf webservice开发)

cxf webservice(cxf webservice开发)

web.xml


!-- 加载spring容器配置 -->
<listener>
    listener-class>org.springframework.web.context.ContextLoaderListener</>
<!-- 设置spring容器加载配置文件路径 -->
context-paramparam-name>contextConfigLocationparam-value>classpath*:applicationContext-server.xml>
 
>org.springframework.web.util.IntrospectorCleanupListenerservletservlet-name>CXFServiceservlet-class>org.apache.cxf.transport.servlet.CXFServletservlet-mappingurl-pattern>/api/*
 
 
接口
package com.hoo.service;
 
import javax.jws.WebParam;
import javax.jws.WebService;
import javax.jws.soap.soAPBinding;
import javax.jws.soap.soAPBinding.Style;
import com.hoo.entity.User;
import com.hoo.entity.Users;
 
/**
 * <b>function:</b>定制客户端请求WebService所需要的接口
 * @author 
 * @createDate 
 * @file ComplexUserService.java
 * @package com.hoo.service
 * @project CXFWebService
 * @version 1.0
 */
@WebService
@SOAPBinding(style = Style.RPC)
public interface IComplexUserService {
    
    public User getUserByName(@WebParam(name = "name") String name);
    
    void setUser(User user);
}
实现类
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
 * <b>function:</b> WebService传递复杂对象,如JavaBean、Array、List、Map等
 */
@WebService
@SOAPBinding(style = Style.RPC)
@SuppressWarnings("deprecation")
class ComplexUserService implements IComplexUserService {
    
    "name") String name) {
        User user = new User();
        user.setId(new Date().getSeconds());
        user.setName(name);
        user.setAddress("china");
        user.setEmail(name + "@hoo.com");
        return user;
    }
    
    void setUser(User user) {
        System.out.println("############Server setUser###########");
        System.out.println("setUser:" + user);
    }
}

applicationContext-server.xml
 
bean id="userServiceBean" class="com.hoo.service.ComplexUserService"/>
 
="inMessageInterceptor" ="com.hoo.interceptor.MessageInterceptor">
    constructor-arg  value="receive"/>
bean>
 
="outLoggingInterceptor" ="org.apache.cxf.interceptor.LoggingOutInterceptor"<!-- 注意下面的address,这里的address的名称就是访问的WebService的name -->
jaxws:server ="userService" serviceClass="com.hoo.service.IComplexUserService" address="/Users"jaxws:serviceBean>
        <!-- 要暴露的 bean 的引用 -->
        ref ="userServiceBean"/>
    jaxws:inInterceptors="inMessageInterceptor"jaxws:outInterceptors="outLoggingInterceptor">
jaxws:server
客户端
class SpringUsersWsClient {
 
    static void main(String[] args) {
        //调用WebService
        JaxWsProxyfactorybean factory = new JaxWsProxyfactorybean();
        factory.setServiceClass(IComplexUserService.class);
        factory.setAddress("http://localhost:8080/CXFWebService/Users");
        
        IComplexUserService service = (IComplexUserService) factory.create();
        
        System.out.println("#############Client getUserByName##############");
        User user = service.getUserByName("hoojo");
        System.out.println(user);
        
        user.setAddress("China-Guangzhou");
        service.setUser(user);
    }
}

将Client端也通过Spring配置完成整合
jaxws:client ="userWsClient" ="com.hoo.service.IComplexUserService" 
        ="http://localhost:8080/CXFWebService/Users"/>

void main(String[] args) {
        ApplicationContext ctx = new ClasspathXmlApplicationContext("applicationContext-client.xml");
        
        IComplexUserService service = ctx.getBean("userWsClient",IComplexUserService.class);
        
        System.out.println("China-Guangzhou");
        service.setUser(user);
    }
}

(webservice+cxf+mybatis+mysql+springmvc) webservice + cxf 能够跑起来的cxf ,来这里,,

(webservice+cxf+mybatis+mysql+springmvc) webservice + cxf 能够跑起来的cxf ,来这里,,

 

webservice jar 下载:  http://download.csdn.net/download/knight_black_bob/9186507

webservice server  下载:http://download.csdn.net/download/knight_black_bob/9186521

webservice client    下载:http://download.csdn.net/download/knight_black_bob/9186517

综合下载:http://download.csdn.net/download/knight_black_bob/9186535

 

user 实例 来自 :

springmvc+mybatis+MysqL 自动生成代码 http://knight-black-bob.iteye.com/blog/2208162

 

 

0 准备工作 jar 下载

cxf-2.6.1.jar geronimo-annotation_1.0_spec-1.1.1.jar geronimo-jaxws_2.2_spec-1.1.jar geronimo-ws-Metadata_2.0_spec-1.1.3.jar neethi-3.0.2.jar slf4j-api-1.6.2.jar wsdl4j-1.6.2.jar xmlschema-core-2.0.2.jar jetty-continuation-7.5.4.v20111024.jar jetty-http-7.5.4.v20111024.jar jetty-io-7.5.4.v20111024.jar jetty-server-7.5.4.v20111024.jar jetty-util-7.5.4.v20111024.jar

 

 

 

1.webservice server

1.1 service 接口

package cn.com.baoy.service; import java.util.List; import javax.jws.WebService; import javax.jws.soap.soAPBinding; import javax.jws.soap.soAPBinding.Style; import org.springframework.stereotype.Service; import cn.com.baoy.bean.User; /** * @author baoyou E-mail:curIoUsby@163.com * @version 创建时间:2015年10月13日 上午11:13:28 * des: */ @WebService @SOAPBinding(style = Style.RPC) public interface UserService { public String sayHello(String string); public List<User> allUser(); public void delUser(Integer userId); public User user(Integer userId); public void updateUser(User user); public void addUser(User user); }

 

 1.2 serviceimpl 接口实现

 

package cn.com.baoy.service.impl; import java.util.List; import javax.jws.WebService; import javax.jws.soap.soAPBinding; import javax.jws.soap.soAPBinding.Style; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import cn.com.baoy.bean.User; import cn.com.baoy.dao.UserDao; import cn.com.baoy.service.UserService; @Service @WebService(endpointInterface="cn.com.baoy.service.UserService",serviceName="UserService") @SOAPBinding(style = Style.RPC) public class UserServiceImpl implements UserService { @Autowired UserDao dao; public String sayHello(String string){ return "test : "+string; } public List<User> allUser(){ return dao.allUser(); } public void delUser(Integer userId){ dao.delUser(userId); } public User user(Integer userId){ return dao.user(userId); } public void updateUser(User user){ dao.updateUser(user); } public void addUser(User user){ dao.addUser(user); } }

 

 1.3application-cxf.xml

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:jaxws="http://cxf.apache.org/jaxws" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd" default-autowire="byName"> <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" /> <bean id="inMessageInterceptor"/> <bean id="outLoggingInterceptor"/> <jaxws:endpoint implementor="cn.com.baoy.service.impl.UserServiceImpl" address="/userService"></jaxws:endpoint> </beans>

 

 1.4 test-servlet

 

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd " default-autowire="byName"> <!-- 数据源 --> <bean id="dataSource"destroy-method="close"> <property name="driverClassName"> <value>com.MysqL.jdbc.Driver</value> </property> <property name="url"> <value>jdbc:MysqL://localhost:3306/database?useUnicode=true&amp;characterEncoding=utf8</value> </property> <property name="username"> <value>root</value> </property> <property name="password"> <value>root</value> </property> </bean> <!-- 自动扫描controller bean,把作了注解的类转换为bean --> <context:component-scan base-package="cn.com.baoy" /> <!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 --> <bean/> <!-- 对模型视图名称的解析,在请求时模型视图名称添加前后缀 --> <!-- <beanp:prefix="" p:suffix=".jsp"> <property name="order" value="0" /> </bean> --> <!-- 创建sqlSessionFactory,同时指定数据源 --> <bean id="sqlSessionFactory"https://www.jb51.cc/tag/sql/" target="_blank">sqlSessionfactorybean"> <property name="dataSource" ref="dataSource"/> <property name="mapperLocations" value="classpath*:cn/com/baoy/mapper/*.xml" /> </bean> <beanhttps://www.jb51.cc/tag/fig/" target="_blank">figurer"> <property name="basePackage" value="cn.com.baoy.dao" /> </bean> </beans>

 

 1.5web.xml

 

 

<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <display-name></display-name> <welcome-file-list> <welcome-file>back/jsp/main.jsp</welcome-file> </welcome-file-list> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/application-cxf.xml /WEB-INF/test-servlet.xml</param-value> </context-param> <servlet> <servlet-name>test</servlet-name> <servlet-class>org.springframework.web.servlet.dispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>test</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <servlet> <servlet-name>CXFServlet</servlet-name> <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class> <load-on-startup>2</load-on-startup> </servlet> <servlet-mapping> <servlet-name>CXFServlet</servlet-name> <url-pattern>/WebService/*</url-pattern> </servlet-mapping> </web-app>

 

 

接口发布成功 后



 


 

 

 

 

 

 

 2.0 测试发布接口程序

package cn.com.baoy; import org.apache.cxf.jaxws.JaxWsProxyfactorybean; import cn.com.baoy.service.UserService; public class WSTest { public static void main(String[] args) { //创建WebService客户端代理工厂 JaxWsProxyfactorybean factory = new JaxWsProxyfactorybean(); //注册WebService接口 factory.setServiceClass(UserService.class); //设置WebService地址 factory.setAddress("http://localhost:8080/webserviceserver/WebService/userService"); UserService userService = (UserService)factory.create(); System.out.println("invoke webservice..."); System.out.println("message context is:"+userService.sayHello("baoyou")); System.out.println("message context is:"+userService.user(7).getUserName()); } }

 

 

接口测试 结果:

 

 


 

 

 

 3 webservice client

 

3.1  接口定义

 

package cn.com.baoy.service; import java.util.List; import javax.jws.WebService; import javax.jws.soap.soAPBinding; import javax.jws.soap.soAPBinding.Style; import org.springframework.stereotype.Service; import cn.com.baoy.bean.User; /** * @author baoyou E-mail:curIoUsby@163.com * @version 创建时间:2015年10月13日 上午11:13:28 * des: */ @WebService @SOAPBinding(style=SOAPBinding.Style.RPC) public interface UserService { public String sayHello(String string); public List<User> allUser(); public void delUser(Integer userId); public User user(Integer userId); public void updateUser(User user); public void addUser(User user); }

  

 3.2

 

package cn.com.baoy.controller; import java.util.List; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import cn.com.baoy.bean.User; import cn.com.baoy.service.UserService; @Controller public class UserController { @Autowired UserService userService; @RequestMapping(value = "/userView.do") public String userView(ModelMap modelMap,String pageNo,String choice,HttpSession session){ List<User> userList = userService.allUser(); modelMap.put("userList",userList); return "back/jsp/user/userView"; } @RequestMapping(value = "/userDel{userId}.do") public String userDel(@PathVariable("userId")int userId,ModelMap modelMap,HttpSession session){ userService.delUser(userId); String message1="删除成功"; String message2="请返回……"; String url="userView.do"; modelMap.put("message1",message1); modelMap.put("message2",message2); modelMap.put("url",url); return "infomationShow"; } @RequestMapping(value ="/userGoAdd.do") public String userGoAdd(ModelMap modelMap,HttpSession session){ return "back/jsp/user/userAdd"; } @RequestMapping(value = "/userAdd.do",method=RequestMethod.POST) public String userAdd(User form,HttpSession session){ userService.addUser(form); String message1="添加成功"; String message2="请返回……"; String url="userView.do"; modelMap.put("message1",message2); modelMap.put("url",url); return "infomationShow"; } @RequestMapping(value = "/userGoUpdate{userId}.do") public String userGoUpdate(@PathVariable("userId")int userId,HttpSession session){ User user = userService.user(userId); modelMap.put("user",user); return "back/jsp/user/userUpdate"; } @RequestMapping(value = "/userUpdate.do",method=RequestMethod.POST) public String userUpdate(User form,HttpSession session){ userService.updateUser(form); String message1="修改成功"; String message2="请返回……"; String url="userView.do"; modelMap.put("message1",url); return "infomationShow"; } }

 

 

 3.3 application-service.xml

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:jaxws="http://cxf.apache.org/jaxws" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.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:client id="userService" serviceaddress="http://localhost:8080/webserviceserver/WebService/userService"/> </beans>

 

 3.4 web.xml

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd " default-autowire="byName"> <bean id="propertyConfigurer"https://www.jb51.cc/tag/fig/" target="_blank">fig.PropertyPlaceholderConfigurer"> <property name="location"> <value>/WEB-INF/config.properties</value> </property> </bean> <!-- 数据源 --> <bean id="dataSource"destroy-method="close"> <property name="driverClassName"> <value>com.MysqL.jdbc.Driver</value> </property> <property name="url"> <value>jdbc:MysqL://localhost:3306/database?useUnicode=true&amp;characterEncoding=utf8</value> </property> <property name="username"> <value>root</value> </property> <property name="password"> <value>root</value> </property> </bean> <!-- 自动扫描controller bean,把作了注解的类转换为bean --> <context:component-scan base-package="cn.com.baoy" /> <!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 --> <bean/> <!-- 对模型视图名称的解析,在请求时模型视图名称添加前后缀 --> <beanp:prefix="" p:suffix=".jsp"> <property name="order" value="0" /> </bean> <!-- 创建sqlSessionFactory,同时指定数据源 --> <bean id="sqlSessionFactory"https://www.jb51.cc/tag/sql/" target="_blank">sqlSessionfactorybean"> <property name="dataSource" ref="dataSource"/> <property name="mapperLocations" value="classpath*:cn/com/baoy/mapper/*.xml" /> </bean> <beanhttps://www.jb51.cc/tag/fig/" target="_blank">figurer"> <property name="basePackage" value="cn.com.baoy.dao" /> </bean> </beans>

 

 

 

 测试 跑通程序



 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

捐助开发者

在兴趣的驱动下,写一个免费的东西,有欣喜,也还有汗水,希望你喜欢我的作品,同时也能支持一下。 当然,有钱捧个钱场(右上角的爱心标志,支持支付宝和PayPal捐助),没钱捧个人场,谢谢各位。


   谢谢您的赞助,我会做的更好!

CXF Webservice 6 - Spring 3 整合Apache CXF WebService

CXF Webservice 6 - Spring 3 整合Apache CXF WebService

在CXF2版本中,整合Spring3发布CXF WebService就更加简单了。因为Spring 3提供了annotation注解,而CXF2发布WebService已经不像之前版本的配置那样(参考老版本发布WebService系列文章:http://www.cnblogs.com/hoojo/archive/2011/03/30/1999563.html),现在发布一个WebService可以直接从Spring的IoC容器中拿到一个对象,发布成WebService服务。当然发布WebService的配置有了些小小的变动,具体请往下看。

 

在老版本中发布一个WebService,配置applicationContext-server.xml文件中添加如下配置如下:

jaxws:server的发布方式

<bean id="userServiceBean" class="com.hoo.service.ComplexUserService"/>
 
<bean id="inMessageInterceptor" class="com.hoo.interceptor.MessageInterceptor">
    <constructor-arg  value="receive"/>
</bean>
<bean id="outLoggingInterceptor" class="org.apache.cxf.interceptor.LoggingOutInterceptor"/>
<!-- 注意下面的address,这里的address的名称就是访问的WebService的name -->
<jaxws:server id="userService" serviceClass="com.hoo.service.IComplexUserService" address="/Users">
    <jaxws:serviceBean>
        <!-- 要暴露的 bean 的引用 -->
        <ref bean="userServiceBean"/>
    </jaxws:serviceBean>
    <jaxws:inInterceptors>
        <ref bean="inMessageInterceptor"/>
    </jaxws:inInterceptors>
    <jaxws:outInterceptors>
        <ref bean="outLoggingInterceptor"/>
    </jaxws:outInterceptors>
</jaxws:server>

jaxws:endpoint的发布方式

<!-- com.hoo.service.ComplexUserService是com.hoo.service.IComplexUserService接口的实现, 这种方法应该不能从Ioc中引用对象 -->
<jaxws:endpoint id="userService2" implementor="com.hoo.service.ComplexUserService" address="/Users">
    <jaxws:inInterceptors>
        <ref bean="inMessageInterceptor"/>
    </jaxws:inInterceptors>
    <jaxws:outInterceptors>
        <ref bean="outLoggingInterceptor"/>
    </jaxws:outInterceptors>
</jaxws:endpoint>

而在2.x新版本中,发布Ioc容器中的对象为一个WebService的方法

<!-- 注意下面的address,这里的address的名称就是访问的WebService的name;#userServiceBean是直接引用Ioc容器中的Bean对象 -->
<jaxws:server id="userService" serviceBean="#userServiceBean" address="/Users">
</jaxws:server>
<!-- 或者这种方式,在老版本中这个是不能引用Ioc容器中的对象,但在2.x中可以直接用#id或#name的方式发布服务 -->
<jaxws:endpoint id="userService2" implementor="#userServiceBean" address="/Users">
</jaxws:endpoint>

CXF发布WebService官方参考:http://cxf.apache.org/docs/writing-a-service-with-spring.html

CXF WebService 7 - Spring整合CXF,发布RSETful 风格WebService

CXF WebService 7 - Spring整合CXF,发布RSETful 风格WebService

这篇文章是承接之前CXF整合Spring的这个项目示例的延伸,所以有很大一部分都是一样的。关于发布CXF WebServer和Spring整合CXF这里就不再多加赘述了。如果你对Spring整合CXF WebService不了解,具体你可以参看这两篇文章:

http://www.cnblogs.com/hoojo/archive/2011/03/30/1999563.html

http://www.cnblogs.com/hoojo/archive/2012/07/13/2590593.html

如果你不了解restful风格的WebService,你可以参考:

http://www.oracle.com/technetwork/articles/javase/index-137171.html

SpringMVC对RESTful的支持:

http://www.cnblogs.com/hoojo/archive/2011/06/10/2077422.html

使用 Jersey框架,搭建RESTful WebService(这个也比较简单)

http://www.ibm.com/developerworks/cn/web/wa-aj-tomcat/

官方文档:http://jersey.java.net/nonav/documentation/latest/user-guide.html#d4e8

其中,比较常用的RESTful框架就有Jersey、Spring REST、CXF RESTful,这些都可以很好的整合Spring框架,发布也相当的简单。且简单、易用、易上手,文档也比较丰富。

 

开发环境:

System:Windows

JavaEE Server:tomcat6

JavaSDK: jdk6+

IDE:eclipse、MyEclipse 6.6

 

开发依赖库:

JDK6、 JavaEE5、CXF-2.3.3、Spring 3.0.4

Email:hoojo_@126.com

Blog:http://blog.csdn.net/IBM_hoojo

http://hoojo.cnblogs.com/

http://hoojo.blogjava.net

 

下面我们就接着http://www.cnblogs.com/hoojo/archive/2011/03/30/1999563.html这篇文章,开始我们CXF RESTful WebService的旅程,enjoy~!^_*

 

准备工作

首先,你需要添加相关的jar包

image

其中,jsr331-api-1.1.1.jar是必须的,利用CXF发布REST服务得用到它,在cxf的lib库中可以找到这个jar。

下载地址:http://www.apache.org/dyn/closer.cgi?path=/cxf/2.3.11/apache-cxf-2.3.11.zip

其它的jar包都是非必须的!

JavaEntity

package com.hoo.entity;
 
import java.util.Map;
import javax.xml.bind.annotation.XmlRootElement;
 
/**
 * <b>function:</b> MapBean 封装Map集合元素
 * @author hoojo
 * @createDate 2012-7-20 下午01:22:31
 * @file MapBean.java
 * @package com.hoo.entity
 * @project CXFWebService
 * @blog http://blog.csdn.net/IBM_hoojo
 * @email hoojo_@126.com
 * @version 1.0
 */
@XmlRootElement
public class MapBean {
    private Map<String,User> map;
    
    //@XmlElement(type = User.class)
    public Map<String,User> getMap() {
        return map;
    }
    public void setMap(Map<String,User> map) {
        this.map = map;
    }
}

 

import java.util.HashMap;
import java.util.List;
import javax.xml.bind.annotation.XmlRootElement;
/**
 * <b>function:</b> Users Entity
 * @author hoojo
 * @createDate 2011-3-18 上午09:27:31
 * @file Users.java
 * @package com.hoo.entity
 * @project CXFWebService
 * @blog http://blog.csdn.net/IBM_hoojo
 * @email hoojo_@126.com
 * @version 1.0
 */
@XmlRootElement(name = "UserInfos")
public class Users {
    private List<User> users;
    
    private User[] userArr;
    private HashMap<String,User> maps;
   // getter/setter
}
import java.io.Serializable;
 * <b>function:</b>User Entity
 * @createDate Dec 16,2010 10:20:02 PM
 * @file User.java
 * @project AxisWebService
@XmlRootElement(name = "UserInfo")
public class User implements Serializable {
    private static final long serialVersionUID = 677484458789332877L;
    private int id;
    private String name;
    private String email;
    private String address;
    //getter/setter
    @Override
    public String toString() {
        return this.id + "#" + this.name + "#" + this.email + "#" + this.address;
}

一、定义你的WebService的接口RESTSample.java,代码如下

package com.hoo.service;
 
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import com.hoo.entity.MapBean;
import com.hoo.entity.User;
import com.hoo.entity.Users;
 
/*
     注释(Annotation):在 javax.ws.rs.* 中定义,是 JAX-RS (JSR 311) 规范的一部分。 
    @Path:定义资源基 URI。由上下文根和主机名组成,资源标识符类似于 http://localhost:8080/RESTful/rest/hello。 
    @GET:这意味着以下方法可以响应 HTTP GET 方法。 
    @Produces:以纯文本方式定义响应内容 MIME 类型。
    
    @Context: 使用该注释注入上下文对象,比如 Request、Response、UriInfo、ServletContext 等。 
    @Path("{contact}"):这是 @Path 注释,与根路径 “/contacts” 结合形成子资源的 URI。 
    @PathParam("contact"):该注释将参数注入方法参数的路径,在本例中就是联系人 id。其他可用的注释有 @FormParam、@QueryParam 等。 
    @Produces:响应支持多个 MIME 类型。在本例和上一个示例中,APPLICATION/XML 将是默认的 MIME 类型。
 */
/**
 * <b>function:</b> CXF RESTful风格WebService
 * @author hoojo
 * @createDate 2012-7-20 下午01:23:04
 * @file RESTSampleSource.java
 * @package com.hoo.service
 * @project CXFWebService
 * @blog http://blog.csdn.net/IBM_hoojo
 * @email hoojo_@126.com
 * @version 1.0
 */
@Path(value = "/sample")
public interface RESTSample {
    
    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String doGet();
    @Path("/request/{param}")
    public String doRequest(@PathParam("param") String param,
            @Context HttpServletRequest servletRequest,@Context HttpServletResponse servletResponse);
    @Path("/bean/{id}")
    @Produces({ MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON })
    public User getBean(@PathParam("id") int id);
    
    @GET
    @Path("/list")
    @Produces({ MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML })
    public Users getList();
    @Path("/map")
    public MapBean getMap();
    /*
        @Consumes:声明该方法使用 HTML FORM。 
        @FormParam:注入该方法的 HTML 属性确定的表单输入。 
        @Response.created(uri).build(): 构建新的 URI 用于新创建的联系人(/contacts/{id})并设置响应代码(201/created)。
        您可以使用 http://localhost:8080/Jersey/rest/contacts/<id> 访问新联系人
     */
    @POST
    @Path("/postData")
    public User postData(User user) throws IOException;
    @PUT
    @Path("/putData/{id}")
    @Consumes(MediaType.APPLICATION_XML)
    public User putData(@PathParam("id") int id,User user);
    @DELETE
    @Path("/removeData/{id}")
    public void deleteData(@PathParam("id") int id);
}

 

二、RESTSample接口的实现,这里我们只是简单的实现下,并不是涉及实际的具体业务

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.UriInfo;
public class RESTSampleSource implements RESTSample {
    @Context
    private UriInfo uriInfo;
    @Context
    private Request request;
    @Produces(MediaType.TEXT_PLAIN)
    public String doGet() {
        return "this is get rest request";
    }
    @Path("/request/{param}")
ottom-style:none; text-align:left; padding-bottom:0px; line-height:12pt; border-right-style:none; background-color:white; margin:0em; padding-left:0px; width:100%; padding-right:0px; font-family:''Courier New'', ottom-style:none; text-align:left; padding-bottom:0px; line-height:12pt; border-right-style:none; background-color:#f4f4f4; margin:0em; padding-left:0px; width:100%; padding-right:0px; font-family:''Courier New'',@Context HttpServletResponse servletResponse) {
        System.out.println(servletRequest);
        System.out.println(servletResponse);
        System.out.println(servletRequest.getParameter("param"));
        System.out.println(servletRequest.getContentType());
        System.out.println(servletResponse.getCharacterEncoding());
        System.out.println(servletResponse.getContentType());
        return "success";
    @Path("/bean/{id}")
ottom-style:none; text-align:left; padding-bottom:0px; line-height:12pt; border-right-style:none; background-color:#f4f4f4; margin:0em; padding-left:0px; width:100%; padding-right:0px; font-family:''Courier New'',MediaType.APPLICATION_JSON })
    public User getBean(@PathParam("id") int id) {
        System.out.println("####getBean#####");
        System.out.println("id:" + id);
        System.out.println("Method:" + request.getmethod());
        System.out.println("uri:" + uriInfo.getPath());
        System.out.println(uriInfo.getPathParameters());
        
        User user = new User();
        user.setId(id);
        user.setName("JojO");
        return user;
    public Users getList() {
        System.out.println("####getList#####");
        System.out.println("Method:" + request.getmethod());
        System.out.println("uri:" + uriInfo.getPath());
        System.out.println(uriInfo.getPathParameters());
        
        List<User> list = new ArrayList<User>();
        User user = null;
        for (int i = 0; i < 4;i ++) {
            user = new User();
            user.setId(i);
            user.setName("JojO-" + i);
            list.add(user);
        }
        Users users = new Users();
        users.setUsers(list);
        return users;
    @Path("/map")
    public MapBean getMap() {
        System.out.println("####getMap#####");
        Map<String,User> map = new HashMap<String,User>();
            map.put("key-" + i,user);
        MapBean bean = new MapBean();
        bean.setMap(map);
        return bean;
    }    
    public User postData(User user) throws IOException {
        System.out.println(user);
        user.setName("jojo##12321321");
        return user;
    } 
    @PUT
    @Path("/putData/{id}")
    @Produces({ MediaType.APPLICATION_XML })
ottom-style:none; text-align:left; padding-bottom:0px; line-height:12pt; border-right-style:none; background-color:#f4f4f4; margin:0em; padding-left:0px; width:100%; padding-right:0px; font-family:''Courier New'',User user) {
        System.out.println("#####putData#####");
        user.setAddress("hoojo#gz");
        user.setEmail("hoojo_@126.com");
        user.setName("hoojo");
        System.out.println(user);
    }
    public void deleteData(@PathParam("id") int id) {
        System.out.println("#######deleteData#######" + id);
}
三、配置我们的WebService,修改applicationContext-server.xml。这里主要是添加jaxrs标签的支持,修改头部文件如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jaxws="http://cxf.apache.org/jaxws"
    xmlns:jaxrs="http://cxf.apache.org/jaxrs"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://cxf.apache.org/jaxws 
    http://cxf.apache.org/schemas/jaxws.xsd
    http://cxf.apache.org/jaxrs
    http://cxf.apache.org/schemas/jaxrs.xsd">
特别注意上面加粗带下划线的部分,这是新增加的配置。我们发布restful WebService需要用到它。
然后在配置文件中添加如下配置
<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"/>
<bean id="restSample" class="com.hoo.service.RESTSampleSource"/>
<!-- 这里的地址很重要,客户端需要通过这个地址来访问WebService -->
<jaxrs:server id="restServiceContainer" address="/rest">
    <jaxrs:serviceBeans>
        <ref bean="restSample" />
    </jaxrs:serviceBeans>
    <jaxrs:extensionMappings>
        <entry key="json" value="application/json" />
        <entry key="xml" value="application/xml" />
    </jaxrs:extensionMappings>
    <jaxrs:languageMappings>
           <entry key="en" value="en-gb"/>  
    </jaxrs:languageMappings>
</jaxrs:server>

这样服务器端就完成了CXF RESTful WebService的发布,启动你的tomcat。然后在浏览器中服务地址:http://localhost:8000/CXFWebService/ (其实这里请求的是CXFServlet,你可以看看上一篇Spring整合CXF文章的web.xml的配置)

你就可以看到我们这里刚刚发布的RESTSample rest的WebService

image

 

你也可以看看里面的xml,也就是WebService的wsdl文件内容。我们找一个GET方式的WebService的方法,在浏览器中调用一下试试

http://localhost:8000/CXFWebService/rest/sample/bean/123

这个url对应到下面这个方法

@GET
@Path("/bean/{id}")
@Produces({ MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON })
public User getBean(@PathParam("id") int id)

结果如下

image

一篇xml文档内容。

 

四、编写客户端代码,调用RESTful WebService

package com.hoo.client;
import java.io.IOException;
import javax.ws.rs.core.MediaType;
import org.apache.cxf.jaxrs.client.WebClient;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClasspathXmlApplicationContext;
import com.hoo.entity.MapBean;
import com.hoo.entity.User;
import com.hoo.entity.Users;
import com.hoo.service.RESTSample;
 * <b>function:</b> RESTful风格WebService
 * @createDate 2012-7-20 下午03:31:03
 * @file RSETServiceClient.java
 * @package com.hoo.client
public class RSETServiceClient {
    private static WebClient client;
    @Before
    public void init() {
        // 手动创建webClient对象,注意这里的地址是发布的那个/rest地址
        //String url = "http://localhost:8000/CXFWebService/rest/";
        //client = WebClient.create(url);
        // 从Spring Ioc容器中拿webClient对象
        ApplicationContext ctx = new ClasspathXmlApplicationContext("applicationContext-client.xml");
        client = ctx.getBean("webClient",WebClient.class);
    @After
    public void destory(){
    @Test
    public void testGet() {
        System.out.println(client.path("sample").accept(MediaType.TEXT_PLAIN).get(String.class));
    @Test
    public void testRequest() {
        System.out.println(client.path("sample/request/234234").accept(MediaType.TEXT_PLAIN).get(String.class));
    public void testBean() {
        User user = client.path("sample/bean/{id}",25).accept(MediaType.APPLICATION_XML).get(User.class);
        System.out.println(user);
    public void testList() {
        System.out.println(client.path("sample/list").accept(MediaType.APPLICATION_XML).get(Users.class).getUsers());
    public void testMap() {
        System.out.println(client.path("sample/map").accept(MediaType.APPLICATION_XML).get(MapBean.class).getMap());
    public void testDeleteData() {
        client.path("sample/removeData/23").delete();
    public void testPostData() {
        User user = new User();
        user.setId(21432134);
        user.setAddress("hoojo#gz");
        user.setEmail("hoojo_@126.com");
        user.setName("hoojo");
        System.out.println(client.path("sample/postData").accept(MediaType.APPLICATION_XML).post(user,User.class));
    public void testPutData() {
        System.out.println(client.path("sample/putData/1").accept(MediaType.APPLICATION_XML).put(user).getEntity());
}
如果你喜欢用Spring的方式,还需要在applicationContext-client.xml中增加如下配置
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://cxf.apache.org/jaxws 
    http://cxf.apache.org/schemas/jaxws.xsd">
    <bean id="webClient" class="org.apache.cxf.jaxrs.client.WebClient" factory-method="create">
        <constructor-arg type="java.lang.String" value="http://localhost:8000/CXFWebService/rest/" />
    </bean>
</beans>

这种是利用WebClient对象来调用WebService,还有一种方法也可以调用WebService,代码如下:

// 手动创建
//RESTSample sample = JAXRSClientFactory.create("http://localhost:8000/CXFWebService/rest",RESTSample.class);
// 从Spring Ioc容器中拿webClient对象
ApplicationContext ctx = new ClasspathXmlApplicationContext("applicationContext-client.xml");
RESTSample sample = ctx.getBean("restSampleBean",RESTSample.class);
System.out.println(sample);
System.out.println(sample.doGet());
//System.out.println(sample.doRequest("haha",null,null));
System.out.println(sample.getBean(22));
System.out.println(sample.getList());
System.out.println(sample.getMap().getMap());
User user = new User();
user.setId(21432134);
user.setAddress("hoojo#gz");
user.setEmail("hoojo_@126.com");
user.setName("hoojo");
System.out.println(sample.postData(user));
System.out.println(sample.putData(111,user));
sample.deleteData(2);

这种方式相对比WebClient要简单,直接使用接口中的方法即可。同样如果你要整合到Spring可以在applicationContext-client.xml中增加配置如下:

<bean id="restSampleBean" class="org.apache.cxf.jaxrs.client.JAXRSClientFactory" factory-method="create">
    <constructor-arg type="java.lang.String" value="http://localhost:8000/CXFWebService/rest/" />
    <constructor-arg type="java.lang.class" value="com.hoo.service.RESTSample" />
</bean>

 

执行以上方法可以看到控制台打印结果如下:

client console
org.apache.cxf.jaxrs.client.ClientProxyImpl@1cf7491
this is get rest request
22#JojO#null#null
com.hoo.entity.Users@16eb6bc
{key-0=0#JojO-0#null#null,key-1=1#JojO-1#null#null,key-2=2#JojO-2#null#null,key-3=3#JojO-3#null#null}
21432134#jojo##12321321#hoojo_@126.com#hoojo#gz
111#hoojo#hoojo_@126.com#hoojo#gz
server console
####getBean#####
id:22
Method:GET
uri:sample/bean/22
{id=[22]}
####getList#####
uri:sample/list
{}
####getMap#####
uri:sample/map
21432134#hoojo#hoojo_@126.com#hoojo#gz
#####putData#####
111#hoojo#hoojo_@126.com#hoojo#gz
#######deleteData#######2

就这样,整合restful WebService成功。

 

****************************************************************************************************

<jaxrs:server id="restServiceContainer" address="/rest">
<jaxrs:serviceBeans>
<ref bean="restSample" />
</jaxrs:serviceBeans>
请问这里bean的值有什么特殊要求吗

 

就是spring容器中的Bean对象,并且相关的WebService方法和类需要添加对应的@annotated

CXF介绍及用 cxf 做的 webservice 简单例子

CXF介绍及用 cxf 做的 webservice 简单例子

 Apache CXF 是一个开放源代码框架,提供了用于方便地构建和开发 Web 服务的可靠基础架构。它允许创建高性能和可扩展的服务,您可以将这样的服务部署在 Tomcat 和基于 Spring 的轻量级容器中,以及部署在更高级的服务器上,例如 Jboss、IBM® WebSphere® 或 BEA WebLogic。

 

       该框架提供了以下功能:

  • Web 服务标准支持:CXF 支持以下 Web 服务标准:
    • Java API for XML Web Services (JAX-WS)
    • SOAP
    • Web 服务描述语言(Web Services Description Language ,WSDL)
    • 消息传输优化机制(Message Transmission Optimization Mechanism,MTOM)
    • WS-Basic Profile
    • WS-Addressing
    • WS-Policy
    • WS-ReliableMessaging
    • WS-Security
  • 前端建模:CXF 提供了前端建模的概念,允许您使用不同的前端 API 来创建 Web 服务。API 允许您使用简单的工厂 Bean 并通过 JAX-WAS 实现来创建 Web 服务。它还允许您创建动态 Web 服务客户端。
  • 工具支持:CXF 提供了用于在 Java Bean、Web 服务和 WSDL 之间进行转换的不同工具。它提供了对 Maven 和 Ant 集成的支持,并无缝地支持 Spring 集成。
  • RESTful 服务支持:CXF 支持代表性状态传输(Representational State Transfer,RESTful )服务的概念,并支持 Java 平台的 JAX-RS 实现。(本系列的第 2 部分将提供有关 RESTful 服务的更多信息。)
  • 对不同传输和绑定的支持:CXF 支持不同种类的传输,从 XML 到逗号分隔值 (CSV)。除了支持 SOAP 和 HTTP 协议绑定之外,它还支持 Java Architecture for XML Binding (JAXB) 和 AEGIS 数据绑定。
  • 对非 XML 绑定的支持:CXF 支持非 XML 绑定,例如 JavaScript Object Notation (JSON) 和 Common Object Request broker Architecture (CORBA)。它还支持 Java 业务集成(Java Business Integration,JBI)体系架构和服务组件体系架构(Service Component Architecture,SCA)。
  • code first 或者 xml first  : 支持使用code first 或者 xml first 的方式来创建web服务。

       一  借助 annotation 创建独立启动的web 服务。

       准备: 新建工程 导入需要的jar 包:

                  

                  依赖的包:

                            commons-logging-1.1.jar
                            geronimo-activation_1.1_spec-1.0-M1.jar (or Sun''s Activation jar)
                            geronimo-annotation_1.0_spec-1.1.jar (JSR 250)
                            geronimo-javamail_1.4_spec-1.0-M1.jar (or Sun''s JavaMail jar)
                            geronimo-servlet_2.5_spec-1.1-M1.jar (or Sun''s Servlet jar)
                            geronimo-ws-Metadata_2.0_spec-1.1.1.jar (JSR 181)
                            jaxb-api-2.1.jar
                            jaxb-impl-2.1.6.jar
                            jaxws-api-2.1.jar
                            jetty-6.1.5.jar
                            jetty-util-6.1.5.jar
                            neethi-2.0.jar
                            saaj-api-1.3.jar
                            saaj-impl-1.3.jar
                            stax-api-1.0.1.jar
                            wsdl4j-1.6.1.jar
                            wstx-asl-3.2.1.jar
                            XmlSchema-1.2.jar
                            xml-resolver-1.2.jar     

                  spring jar 包, 用来支持xml配置:

                            aopalliance-1.0.jar
                            spring-core-2.0.4.jar
                            spring-beans-2.0.4.jar
                            spring-context-2.0.4.jar
                            spring-web-2.0.4.jar

                   CXF jar包:

                            cxf-2.1.jar

   

         以上jar 包 可从apache官方网站下载 apache-cxf-2.1.2.zip, 然后从apache-cxf-2.1.2/lib 目录中获得

      1  首先服务点接口。

          package com.demo;

 

          import java.util.List;

          import javax.jws.WebParam;
          import javax.jws.WebService;
         

          @WebService
          public interface HelloWorld {
               String sayHi(@WebParam(name="text")String text);
               String sayHiToUser(User user);
               String[] SayHiToUserList(List<User> userList);
           }

     2  编写服务实现

         package com.demo;

         import java.util.LinkedHashMap;
         import java.util.List;
         import java.util.Map;

         import javax.jws.WebService;

         @WebService(endpointInterface="com.demo.HelloWorld",serviceName="HelloWorld")
         public class HelloWorldImpl implements HelloWorld {
 
                    Map<Integer,User> users = new LinkedHashMap<Integer,User>();

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

                   public String sayHiToUser(User user) {
                             users.put(users.size()+1,user);
                             return "Hello "+ user.getName();
                   }

                   public String[] SayHiToUserList(List<User> userList) {
                             String[] result = new String[userList.size()];
                             int i=0;
                             for(User u:userList){
                                  result[i] = "Hello " + u.getName();
                                  i++;
                             }
                     return result;
                   }
       }

  3  编写 webServiceApp.java类来暴露 web服务。

      package com.demo;

      import javax.xml.ws.Endpoint;

      public class webServiceApp {
                 public static void main(String[] args) {
                           System.out.println("web service start");
                           HelloWorldImpl implementor= new HelloWorldImpl();
                           String address="
http://localhost:8080/helloWorld";
                           Endpoint.publish(address,implementor);
                           System.out.println("web service started");
                  }
      }

 4  run webServiceApp.java 类来启动服务。 访问 http://localhost:8080/helloWorld?wsdl  查看是否显示

     wsdl。

  

 5  编写客户端访问服务。

     package com.demo;

     import java.util.ArrayList;
     import java.util.List;

     import org.apache.cxf.jaxws.JaxWsProxyfactorybean;
     import org.springframework.context.support.ClasspathXmlApplicationContext;

     public class HelloWorldClient {
              public static void main(String[] args) {
                        JaxWsProxyfactorybean svr = new JaxWsProxyfactorybean();
                        svr.setServiceClass(HelloWorld.class);
                        svr.setAddress("
http://localhost:8080/helloWorld");
                        HelloWorld hw = (HelloWorld) svr.create();
                        User user = new User();
                        user.setName("Tony");
                        user.setDescription("test");
                        System.out.println(hw.sayHiToUser(user));
              }
     }

  6  测试: run webServiceApp.java 类来启动服务,然后 run HelloWorldClient.java 来访问服务。

  二 集成到spring 中。

  

  1 在 web.xml 中加入 :

       <?xml version="1.0" encoding="UTF-8"?>
       <web-app>
                <welcome-file-list>
                         <welcome-file>index.jsp</welcome-file>
                </welcome-file-list>


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

              <servlet>
                     <servlet-name>CXFServlet</servlet-name>
                     <display-name>CXFServlet</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>/webservice/*</url-pattern>
               </servlet-mapping>
         </web-app>

2  在 applicationContext.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="helloWorld"
                              implementor="com.demo.HelloWorldImpl"
                              address="/helloWorld" />
   
                <bean id="client" 
                           factory-bean="clientFactory" factory-method="create"/>
    
                 <bean id="clientFactory"https://www.jb51.cc/tag/factorybean/" target="_blank">factorybean">
                            <property name="serviceClass" value="com.demo.HelloWorld"/>
                            <property name="address"

                                              value="http://localhost:8080/s/webservice/helloWorld"/>
                  </bean>
     </beans>

    注意: 这里需要加入  xmlns:jaxws="http://cxf.apache.org/jaxws"   

              http://cxf.apache.org/schemas/jaxws.xsd

  3  修改客户端。

      package com.demo;

     public class HelloWorldClient {
              public static void main(String[] args) {
                        HelloWorld client = (HelloWorld)context.getBean("client");
                        User user1 = new User();
                        user1.setName("Tony");
                        user1.setDescription("test");
                        User user2 = new User();
                        user2.setName("freeman");
                        user2.setDescription("test");
                        List<User> userList= new ArrayList<User>();
                        userList.add(user1);
                        userList.add(user2);
                        String[] res = client.SayHiToUserList(userList);
                        System.out.println(res[0]);
                        System.out.println(res[1]);          

              }
     }

  4  发布工程 启动web服务器(我用 tomcat 6)。

  5 访问 http://localhost:8080/s/webservice/helloWorld?wsdl  查看是否显示 wsdl 。

 

  6  run run HelloWorldClient.java 来访问服务。

关于cxf webservicecxf webservice开发的问题我们已经讲解完毕,感谢您的阅读,如果还想了解更多关于(webservice+cxf+mybatis+mysql+springmvc) webservice + cxf 能够跑起来的cxf ,来这里,,、CXF Webservice 6 - Spring 3 整合Apache CXF WebService、CXF WebService 7 - Spring整合CXF,发布RSETful 风格WebService、CXF介绍及用 cxf 做的 webservice 简单例子等相关内容,可以在本站寻找。

本文标签: