www.91084.com

GVKun编程网logo

WebService之XFire+Spring集成(使用注解)(spring webflux教程)

5

针对WebService之XFire+Spring集成和使用注解这两个问题,本篇文章进行了详细的解答,同时本文还将给你拓展CXFWebservice6-Spring3整合ApacheCXFWebSer

针对WebService之XFire+Spring集成使用注解这两个问题,本篇文章进行了详细的解答,同时本文还将给你拓展CXF Webservice 6 - Spring 3 整合Apache CXF WebService、CXF WebService 7 - Spring整合CXF,发布RSETful 风格WebService、CXF WebServices 集成Spring、CXF创建webservice服务端、客户端,与spring集成等相关知识,希望可以帮助到你。

本文目录一览:

WebService之XFire+Spring集成(使用注解)(spring webflux教程)

WebService之XFire+Spring集成(使用注解)(spring webflux教程)

        本文只是介绍XFire+Spring使用注解的集成,版本为Xfire 1.2.6+Spring 3.1.1,测试环境为Tomcat6.0。Xfire 1.2.6下载

        1.首先建一个Web工程,引入相应的jar包,Xfire开发最精简jar包下载

服务器端:

commons-logging-1.1.1.jar
jdom-1.0.jar
org.springframework.aop-3.1.1.RELEASE.jar
org.springframework.asm-3.1.1.RELEASE.jar
org.springframework.beans-3.1.1.RELEASE.jar
org.springframework.context-3.1.1.RELEASE.jar
org.springframework.core-3.1.1.RELEASE.jar
org.springframework.expression-3.1.1.RELEASE.jar
org.springframework.web.servlet-3.1.1.RELEASE.jar
org.springframework.web-3.1.1.RELEASE.jar
wsdl4j-1.6.1.jar
xfire-all-1.2.6.jar

客户端:

com.springsource.org.junit-4.7.0.jar
commons-codec-1.3.jar
commons-httpclient-3.0.jar
commons-logging-1.1.1.jar
jdom-1.0.jar
wsdl4j-1.6.1.jar
xfire-all-1.2.6.jar
XmlSchema-1.1.jar

        2.修改web.xml,加入以下代码:

	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:applicationContext.xml</param-value>
	</context-param>

	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<servlet>
		<servlet-name>xfireServlet</servlet-name>
		<servlet-class>org.codehaus.xfire.spring.XFireSpringServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>xfireServlet</servlet-name>
		<url-pattern>/service/*</url-pattern>
	</servlet-mapping>
        3.在classpath下加入Spring配置文件applicationContext.xml,加入以下代码:

	<context:component-scan base-package="my.webservice" />
	
	<!-- XFire start -->
	<import resource="classpath:org/codehaus/xfire/spring/xfire.xml" />
	<bean id="webAnnotations"/>
	<bean id="jsr181HandlerMapping">
		<property name="xfire" ref="xfire" />
		<property name="webAnnotations" ref="webAnnotations" />
	</bean>
	<!-- XFire end -->
        4.定义WebService接口,添加相应注解:

@WebService
public interface IBookService {

	@WebMethod
	public Book getBook();
}
        5.接口实现类,注解中serviceName定义发布的服务名,endpointInterface定义实现的接口:

@Component
@WebService(serviceName="BookService",endpointInterface = "my.webservice.IBookService")
public class BookServiceImpl implements IBookService {

	@Override
	public Book getBook() {
		
		Book b = new Book(1,"Java核心思想",100);
		
		System.out.println(">>>>>>Server: " + b);
		
		return b;
	}
}

        6.以上便是服务端的配置及实现,是不是很简单。把工程发布到Tomcat并启动,在浏览器中输入:http://127.0.0.1:8080/XFireTest/service/BookService?wsdl(BookService为上面serviceName定义的名称),如果浏览器中显示BookService相关xml信息,则表示WebService发布成功。

        7.客户端调用服务端方法:

        (1)使用接口调用,此方法需要发布服务者提供接口,或我们自己通过wsdl生成接口。自己生成接口方法:

wsimport -keep -p my.client http://127.0.0.1:8080/XFireTest/service/BookService?wsdl
-keep 指示保留生成的文件,-p 指定需要在其中生成构件的包名称。http://127.0.0.1:8080/XFireTest/service/BookService?wsdl 是WSDL文件的位置。
wsimport在JAVA_HOME/bin目录下,应该已加到path环境变量中,可直接在cmd中运行以上命令,注意先进入要生成类的目录(如src)再执行。

	@Test
	public void testBookService() {
		Service serviceModel = new ObjectServiceFactory().create(IBookService.class);
		String url = "http://127.0.0.1:8080/XFireTest/service/BookService";
		IBookService service = null;
		
		try {
			service = (IBookService) new XFireProxyFactory().create(serviceModel,url);
			Book b = service.getBook();
			System.out.println(">>>>>>>>Client: " + b);
		} catch (Exception e) {
			e.printstacktrace();
		}
	}

        (2)通过wsdl调用,该方法如果返回值是String可正常使用,如果像本列中返回Book类型,则打印值为[#document: null],返回类型是org.apache.xerces.dom.DocumentImpl,需手动解析。我在项目中使用时,发布服务的时候把数据用xml形式返回,客户端用dom4j解析。

	@Test
	public void wsdltest() throws MalformedURLException,Exception  {
		Client client = new Client(new URL("http://127.0.0.1:8080/XFireTest/service/BookService?wsdl"));
		Object[] results = client.invoke("getBook",new Object[] {});
		System.out.println(results[0]); 
	}

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 WebServices 集成Spring

CXF WebServices 集成Spring

Spring配置

<?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" /> <!--JAX-WS ednpoint Spring方式配置CXF服务端 --> <jaxws:endpoint id="welcome" implementor="com.ws.WelcomeImpl" address="/welcome"/> <!--JAX-WS server Spring方式配置CXF服务端 --> <jaxws:server id="welcome2" serviceaddress="/welcome2"/> <!--JAX-WS client Spring方式配置CXF客户端 --> <jaxws:client id="welcomeService" serviceaddress="http://localhost:8080/Demo/webservice/welcome2"/> <!-- JAX-WS proxy factory方式配置CXF客户端--> <bean id="clientFactory"https://www.jb51.cc/tag/factorybean/" target="_blank">factorybean"> <property name="serviceClass" value="com.ws.Welcome" /> <property name="address" value="http://127.0.0.1:8080/Demo/webservice/welcome?wsdl" /> </bean> <bean id="welcomeService2"factory-bean="clientFactory" factory-method="create"/> </beans>

web.xml配置

加入Spring和CXF的启动配置
<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> <display-name>CXFServlet</display-name> <servlet-name>CXFServlet</servlet-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>
发布到Tomcat,直接访问:http://localhost:8080/Demo/webservice  可以看到CXF发布的所有SOAP services和RESTful services
http://localhost:8080/Demo/webservice/welcome/getWelcome?name=jock  在服务后面添加方法名,问号后面添加参数,返回服务调用结果。
详细配置参数见:http://cxf.apache.org/docs/jax-ws-configuration.htmlJAXWS frontend server and client spring configuration: http://cxf.apache.org/docs/simple-frontend-configuration.html

CXF创建webservice服务端、客户端,与spring集成

CXF创建webservice服务端、客户端,与spring集成

服务端

1.必须jar包:cxf-2.6.1.jar

2.spring-cxf.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" />

	<bean id="checksystemserviceimp"https://www.jb51.cc/tag/stem/" target="_blank">stem.server.CheckSystemServiceImp">
	</bean>

	<jaxws:endpoint id="webservice" implementor="#checksystemserviceimp"
		address="/webservice">
	</jaxws:endpoint>
</beans>

 

3. web.xml配置spring-cxf.xml

<listener>
   <listener-class>com.chinavvv.util.ContextLoaderListener</listener-class>
 </listener>  
     <context-param>   
        <param-name>contextConfigLocation</param-name>   
        <param-value>/WEB-INF/spring-cxf.xml
        </param-value>

    </context-param>
<!--还需要配置以下servlet-->
<servlet>    
  <servlet-name>CXFService</servlet-name>    
  <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
  <load-on-startup>1</load-on-startup>  
 </servlet> 
 <servlet-mapping>    
  <servlet-name>CXFService</servlet-name>    
  <url-pattern>/service/*</url-pattern>
 </servlet-mapping>


4. java类、接口如下,包含接口CheckSystemService、接口实现类CheckSystemServiceImp

package a.rst.checksystem.server;

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

@WebService
public interface CheckSystemService {
 public void test(@WebParam(name="param") String param);
 public String checkWebSer(String aac002,String aac003,String aab301) throws Exception;
}



 

@WebService(endpointInterface = "a.rst.checksystem.server.CheckSystemService")
public class CheckSystemServiceImp implements CheckSystemService {

public void test(String param) {
  System.out.println("001webservice is success ");
  System.out.println("002dao is annotationed? "+relectdao);
  System.out.println("003url param:"+param);

}

public String checkWebSer(String aac002,String aab301)
   throws Exception {

Ceshibean bean=new CeshiBean();//这里是自定义的Javabean

return jsontToString(PersonalInfo);// 返回类型设置为json格式的字符串,没有使用Bean

}

 
private String jsontToString(Object o){
  JsonConfig jsonConfig = new JsonConfig();  //建立配置文件
   jsonConfig.setIgnoreDefaultExcludes(false);  //设置默认忽略
    jsonConfig.setExcludes(new String[]{"child","multipartRequestHandler","resultValueMap","servletWrapper","validatorResults"}); 
   //net.sf.json.JSONObject jsonbean = net.sf.json.JSONObject.fromObject(bean,jsonConfig);
   JSONObject json = JSONObject.fromObject(o,jsonConfig);
  return json.toString();
 }

}


 

测试是否发布成功地址:http://127.0.0.1:8080/service/webservice?wsdl

 

客户端:

cd d:/java/bin

wsimport - keep -p com.webservice.client http://127.0.0.1:8080/service/webservice?wsdl

用Java api生成客户端包,以上命令将在d:/java/bin目录下生成com.webservice.client包。

今天的关于WebService之XFire+Spring集成使用注解的分享已经结束,谢谢您的关注,如果想了解更多关于CXF Webservice 6 - Spring 3 整合Apache CXF WebService、CXF WebService 7 - Spring整合CXF,发布RSETful 风格WebService、CXF WebServices 集成Spring、CXF创建webservice服务端、客户端,与spring集成的相关知识,请在本站进行查询。

本文标签: