CXF整合Spring发布Rest接口服务,以及客户端如何调用服务端接口

1.创建web工程

2.导入jar包

3.编写接口以及实现类

3.1在编写接口之前需要注意一下这里用到的实体类 需要特别注意:需要在实体类前面添加注解

(XmlRootElement)

package com.zit.entity;

import java.io.Serializable;

import javax.xml.bind.annotation.XmlRootElement;

/**
 *@author: wangq
 *@date: 2015-5-18上午10:14:58
 *@version:
 *@description:
 */

@XmlRootElement
public class User extends BaseEntity implements Serializable{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	/**
	 *  用户ID
	 */
	private Long userId;
	/**
	 *  用户名
	 */
	private String userName;
	/**
	 *  密码
	 */
	private String password;   
	/**
	 *  用户类型
	 */
	private Integer userType;  
	/**
	 *  所属角色ID
	 */
	private Long roleId;    
	/**
	 *  用户描述
	 */
	private String userDescription;  
	/**
	 *  所属角色名称
	 */
	private String roleName;         


	public String getRoleName() {
		return roleName;
	}
	public void setRoleName(String roleName) {
		this.roleName = roleName;
	}
	public Long getUserId() {
		return userId;
	}
	public void setUserId(Long userId) {
		this.userId = userId;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public Integer getUserType() {
		return userType;
	}
	public void setUserType(Integer userType) {
		this.userType = userType;
	}
	public Long getRoleId() {
		return roleId;
	}
	public void setRoleId(Long roleId) {
		this.roleId = roleId;
	}
	public String getUserDescription() {
		return userDescription;
	}
	public void setUserDescription(String userDescription) {
		this.userDescription = userDescription;
	}
	@Override
	public String toString() {
		return "User [userId=" + userId + ", userName=" + userName
				+ ", password=" + password + ", userType=" + userType
				+ ", roleId=" + roleId + ", userDescription=" + userDescription
				+ ", roleName=" + roleName + "]";
	}
	
	
	
}

3.1编写接口

/**  
* <p>Title: HelloCxf.java</p>  
* <p>Description: </p>   
* @author lihongjie  
* @date 2018年8月13日  
* @version 1.0  
*/  
package com.zit.webservice;

import java.io.Serializable;

import javax.jws.WebService;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import com.zit.entity.User;

/**  
* <p>Title: HelloCxf</p>  
* <p>Description: </p>  
* @author lihongjie  
* @date 2018年8月13日  
*/
@WebService
@Path("/helCxf")
public interface HelloCxf extends Serializable{
	@GET//制定请求方式,如果服务端 发布的时候指定的是GET(POST), 那么客户端必须使用GET(POST)
	@Produces(MediaType.APPLICATION_XML)//指定服务数据类型
	@Path("/queryUser/{id}")
	public User queryUser(@PathParam("id")long id);

}

3.2 编写实现类

/**  
* <p>Title: HelloCxfImpl.java</p>  
* <p>Description: </p>   
* @author lihongjie  
* @date 2018年8月13日  
* @version 1.0  
*/  
package com.zit.webservice.impl;



import org.springframework.beans.factory.annotation.Autowired;

import com.zit.entity.User;
import com.zit.service.UserService;
import com.zit.webservice.HelloCxf;

/**  
* <p>Title: HelloCxfImpl</p>  
* <p>Description: </p>  
* @author lihongjie  
* @date 2018年8月13日  
*/
public class HelloCxfImpl implements HelloCxf{

	@Autowired
	private UserService<User> userService; 
	@Override
	public User queryUser(long id) {
		User user = null;
		try {
			user = userService.findOneUser(id);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return user;
	}

}

3.添加spring的配置文件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:p="http://www.springframework.org/schema/p"
  xmlns:context="http://www.springframework.org/schema/context"
  xmlns:mvc="http://www.springframework.org/schema/mvc"
  xmlns:aop="http://www.springframework.org/schema/aop"
  xmlns:tx="http://www.springframework.org/schema/tx"
  xmlns:jaxws="http://cxf.apache.org/jaxws"
  xmlns:jaxrs="http://cxf.apache.org/jaxrs"
  xmlns:cxf="http://cxf.apache.org/core"
  xsi:schemaLocation="http://www.springframework.org/schema/beans 
 http://www.springframework.org/schema/beans/spring-beans-3.1.xsd 
 http://www.springframework.org/schema/context 
 http://www.springframework.org/schema/context/spring-context-3.1.xsd 
 http://www.springframework.org/schema/mvc 
 http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
 http://www.springframework.org/schema/aop 
 http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
 http://www.springframework.org/schema/tx
 http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
 http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd
 http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd
 http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd">
<!-- CXF实现REST服务 -->
  <!-- <jaxrs:server发布REST的服务 ,对JAXRSServerFactoryBean类封装-->	
  <jaxrs:server address="/zVersionWebService">
	<jaxrs:serviceBeans>
		<ref bean="userInterfaceQuery"/>
	</jaxrs:serviceBeans>
  </jaxrs:server>
	<!-- 配置服务实现类 -->
	<bean name="userInterfaceQuery" class="com.zit.webservice.impl.HelloCxfImpl"/>

4.添加web.xml文件的配置

<!-- 配置cxf的servlet -->
  <servlet>
    <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>
<servlet>
    <servlet-name>SpringMVC</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:applicationContext.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
    <async-supported>true</async-supported>
  </servlet>

5.启动Tomcat即可发布rest服务

6.客户端调用

/**  
* <p>Title: HelloCxfRest.java</p>  
* <p>Description: </p>   
* @author lihongjie  
* @date 2018年8月14日  
* @version 1.0  
*/  
package com.zit.webservice.client;


import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.apache.cxf.jaxrs.client.WebClient;

import com.zit.entity.User;

/**  
* <p>Title: HelloCxfRest</p>  
* <p>Description: cxf发布rest服务的客户端测试类</p>  
* @author lihongjie  
* @date 2018年8月14日  
*/
public class HelloCxfRest {
	public static void main(String[] args) {
		
		String baseAddress = "http://localhost:8080/zVision/webservice/zVersionWebService/helCxf";
		WebClient webClient = WebClient.create(baseAddress)
				.path("/queryUser").path("/47");
		Response resp3 = webClient.accept(MediaType.APPLICATION_XML).type(MediaType.APPLICATION_XML).get();
		System.out.println(resp3.getMetadata());
		//readEntity(“方法的返回值类型”)
		System.out.println(resp3.readEntity(User.class));
	}
}

7.控制台运行接口

SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/D:/Oxygenworkspace/zVision/WebContent/WEB-INF/lib/activemq-all-5.6.0.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/D:/Oxygenworkspace/zVision/WebContent/WEB-INF/lib/slf4j-log4j12-1.7.7.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
{Content-Length=[229], content-type=[application/xml], Date=[Tue, 14 Aug 2018 03:14:16 GMT]}
User [userId=47, userName=admin, password=admin, userType=2, roleId=4, userDescription=普通管理员, roleName=null]

8.浏览器访问结果

猜你喜欢

转载自blog.csdn.net/qq_37306041/article/details/81663692