Spring整合ApacheCXF实现基于Restful风格的WebService(基于jaxrs)

1.服务端

1.1 创建web maven项目

Spring整合ApacheCXF实现基于Restful风格的WebService(基于jaxrs)_第1张图片

1.2 添加依赖pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0modelVersion>
	<groupId>org.examplegroupId>
	<artifactId>spring_jaxrs_serverartifactId>
	<packaging>warpackaging>
	<version>0.0.1-SNAPSHOTversion>
	<name>spring_jaxrs_server Maven Webappname>
	<url>http://maven.apache.orgurl>
	<dependencies>
		
		<dependency>
			<groupId>org.apache.cxfgroupId>
			<artifactId>cxf-rt-frontend-jaxrsartifactId>
			<version>3.0.1version>
		dependency>
		
		<dependency>
			<groupId>org.slf4jgroupId>
			<artifactId>slf4j-log4j12artifactId>
			<version>1.7.12version>
			<scope>testscope>
		dependency>
		
		<dependency>
			<groupId>org.apache.cxfgroupId>
			<artifactId>cxf-rt-rs-clientartifactId>
			<version>3.0.1version>
		dependency>
		
		<dependency>
			<groupId>org.apache.cxfgroupId>
			<artifactId>cxf-rt-rs-extension-providersartifactId>
			<version>3.0.1version>
		dependency>
		
		<dependency>
			<groupId>org.codehaus.jettisongroupId>
			<artifactId>jettisonartifactId>
			<version>1.3.7version>
		dependency>
		
		<dependency>
			<groupId>org.springframeworkgroupId>
			<artifactId>spring-contextartifactId>
			<version>4.2.4.RELEASEversion>
		dependency>
		
		<dependency>
			<groupId>org.springframeworkgroupId>
			<artifactId>spring-webartifactId>
			<version>4.2.4.RELEASEversion>
		dependency>
		
		<dependency>
			<groupId>junitgroupId>
			<artifactId>junitartifactId>
			<version>4.12version>
			<scope>testscope>
		dependency>

	dependencies>
	<build>
		<pluginManagement>
			<plugins>
				
				<plugin>
					<groupId>org.apache.maven.pluginsgroupId>
					<artifactId>maven-compiler-pluginartifactId>
					<version>3.2version>
					<configuration>
						<source>1.8source>
						<target>1.8target>
						<showWarnings>trueshowWarnings>
					configuration>
				plugin>
				
				<plugin>
					<groupId>org.apache.tomcat.mavengroupId>
					<artifactId>tomcat7-maven-pluginartifactId>
					<version>2.2version>
					<configuration>
						
						<port>8080port>
						
						<path>/path>
					configuration>
				plugin>
			plugins>
		pluginManagement>
	build>
project>

1.3 web.xml

DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
	<display-name>Archetype Created Web Applicationdisplay-name>

	
	<servlet>
		<servlet-name>cxfServletservlet-name>
		<servlet-class>org.apache.cxf.transport.servlet.CXFServletservlet-class>
	servlet>
	<servlet-mapping>
		<servlet-name>cxfServletservlet-name>
		
		<url-pattern>/ws/*url-pattern>
	servlet-mapping>

	
	<context-param>
		<param-name>contextConfigLocationparam-name>
		<param-value>classpath:applicationContext.xmlparam-value>
	context-param>
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
	listener>
web-app>

1.4 服务实体类

package org.jaxrs.entity;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "Car")
public class Car {

	private Integer id;
	private String carName;
	private Double price;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getCarName() {
		return carName;
	}
	public void setCarName(String carName) {
		this.carName = carName;
	}
	public Double getPrice() {
		return price;
	}
	public void setPrice(Double price) {
		this.price = price;
	}
	@Override
	public String toString() {
		return "Car [id=" + id + ", carName=" + carName + ", price=" + price + "]";
	}
	public Car(Integer id, String carName, Double price) {
		super();
		this.id = id;
		this.carName = carName;
		this.price = price;
	}
	public Car() {
		super();
	}
	
}

package org.jaxrs.entity;

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

import javax.xml.bind.annotation.XmlRootElement;

/**
 *	基于restful风格的webservice,客户端与服务端之间的通讯可以传递xml数据、json数据
 *	 @XmlRootElement 指定对象序列化为xml或json数据时根节点的名称
 *	xml:
 *		
 *			
 *			
 *			
 *		
 *	json:
 *		{"User":{"id":100,"username":"张三","city":"广东"}}
 *
 */
@XmlRootElement(name = "User")
public class User {
	
	private Integer id;
	private String username;
	private String city;
	
	private List<Car> cars = new ArrayList<Car>();

	
	public User() {
		super();
	}

	public User(Integer id, String username, String city, List<Car> cars) {
		super();
		this.id = id;
		this.username = username;
		this.city = city;
		this.cars = cars;
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getCity() {
		return city;
	}

	public void setCity(String city) {
		this.city = city;
	}

	public List<Car> getCars() {
		return cars;
	}

	public void setCars(List<Car> cars) {
		this.cars = cars;
	}

	@Override
	public String toString() {
		return "User [id=" + id + ", username=" + username + ", city=" + city + ", cars=" + cars + "]";
	}
	
}

1.5 服务接口、实现

package org.jaxrs.service;

import java.util.List;

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 org.jaxrs.entity.User;


//@Path 在接口上表示访问当前服务接口对应的路径
//@Produces 值为*/*,支持任意类型,表示服务器支持的返回的数据格式类型
@Path("/userService")
@Produces("*/*")
public interface UserServiceI {
	
	/**
	 *	 @Path 表示访问当前服务接口方法对应的路径。【.../userService/user】
	 *	 @POST 表示处理的请求类型,post对应的是insert新增操作
	 *	 @PUT  表示处理的请求类型,put对应的是update更新操作
	 *	 @GET  表示处理的请求类型,put对应的是query查询操作
	 *	 @DELETE  表示处理的请求类型,put对应的是delete删除操作
	 *	 @Consumes 表示服务器支持的请求的数据格式类型
	 */
	@POST
	@Path("/user")
	@Consumes({"application/xml","application/json"})
	public void saveUser(User user);
	
	@PUT
	@Path("/user")
	@Consumes({"application/xml","application/json"})
	public void updateUser(User user);
	
	@GET
	@Path("/user")
	@Produces({"application/xml","application/json"})
	public List<User> findAllUsers();
	
	@GET
	@Path("/user/{id}")
	@Consumes("application/xml")
	@Produces({"application/xml","application/json"})
	public User findUserById(@PathParam("id") Integer id);
	
	@DELETE
	@Path("/user/{id}")
	@Consumes({"application/xml","application/json"})
	public void deleteUser(@PathParam("id") Integer id);

}

package org.jaxrs.service.impl;

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

import org.jaxrs.entity.Car;
import org.jaxrs.entity.User;
import org.jaxrs.service.UserServiceI;


public class UserServiceImpl implements UserServiceI{

	@Override
	public void saveUser(User user) {
		System.out.println("save user:" + user);
	}

	@Override
	public void updateUser(User user) {
		System.out.println("update user:"+user);
	}

	@Override
	public List<User> findAllUsers() {
		//张三所拥有的汽车集合
		List<Car> cars = new ArrayList<Car>();
		Car car1 = new Car(101,"保时捷",1000000000000d);
		Car car2 = new Car(102,"宝马",4000000d);
		cars.add(car1);
		cars.add(car2);
		
		List<User> users =new ArrayList<User>();
		User user1 = new User(1,"张三","东莞",cars);
		
		User user2 = new User(2,"李四","上海",null);
		
		users.add(user1);
		users.add(user2);
		return users;
	}

	@Override
	public User findUserById(Integer id) {
		if (id == 1) {
			User user = new User(1,"张三","东莞",null);
			return user;
		}
		return null;
	}

	@Override
	public void deleteUser(Integer id) {
		System.out.println("delete user id:"+id);
	}

}

1.6 Spring整合CXF配置applicationContext.xml


<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:cxf="http://cxf.apache.org/core"
    xmlns:jaxws="http://cxf.apache.org/jaxws"
    xmlns:jaxrs="http://cxf.apache.org/jaxrs"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://cxf.apache.org/core
        http://cxf.apache.org/schemas/core.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
        ">
        
        
        
         
         <jaxrs:server address="/userService">
         	<jaxrs:serviceBeans>
         		<bean class="org.jaxrs.service.impl.UserServiceImpl">bean>
         	jaxrs:serviceBeans>
         jaxrs:server>

beans>


1.7 发布服务

Spring整合ApacheCXF实现基于Restful风格的WebService(基于jaxrs)_第2张图片

Spring整合ApacheCXF实现基于Restful风格的WebService(基于jaxrs)_第3张图片

这里一定要设置jdk版本,因为pom.xml设置了maven编译版本为1.8,如果不是jdk1.8,会报错不匹配

控制台没有报错即发布成功

2.客户端

2.1 创建简单maven项目

Spring整合ApacheCXF实现基于Restful风格的WebService(基于jaxrs)_第4张图片

2.2 添加依赖pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0modelVersion>
  <groupId>org.examplegroupId>
  <artifactId>spring_jaxrs_clientartifactId>
  <version>0.0.1-SNAPSHOTversion>
  
  <dependencies>
		
		<dependency>
			<groupId>org.apache.cxfgroupId>
			<artifactId>cxf-rt-frontend-jaxrsartifactId>
			<version>3.0.1version>
		dependency>
		
		<dependency>
			<groupId>org.slf4jgroupId>
			<artifactId>slf4j-log4j12artifactId>
			<version>1.7.12version>
			<scope>testscope>
		dependency>
		
		<dependency>
			<groupId>org.apache.cxfgroupId>
			<artifactId>cxf-rt-rs-clientartifactId>
			<version>3.0.1version>
		dependency>
		
		<dependency>
			<groupId>org.apache.cxfgroupId>
			<artifactId>cxf-rt-rs-extension-providersartifactId>
			<version>3.0.1version>
		dependency>
		
		<dependency>
			<groupId>org.codehaus.jettisongroupId>
			<artifactId>jettisonartifactId>
			<version>1.3.7version>
		dependency>
		
		<dependency>
			<groupId>org.springframeworkgroupId>
			<artifactId>spring-contextartifactId>
			<version>4.2.4.RELEASEversion>
		dependency>
		
		<dependency>
			<groupId>org.springframeworkgroupId>
			<artifactId>spring-webartifactId>
			<version>4.2.4.RELEASEversion>
		dependency>
		
		<dependency>
			<groupId>junitgroupId>
			<artifactId>junitartifactId>
			<version>4.12version>
			<scope>testscope>
		dependency>

	dependencies>
	<build>
		<pluginManagement>
			<plugins>
				
				<plugin>
					<groupId>org.apache.maven.pluginsgroupId>
					<artifactId>maven-compiler-pluginartifactId>
					<version>3.2version>
					<configuration>
						<source>1.8source>
						<target>1.8target>
						<showWarnings>trueshowWarnings>
					configuration>
				plugin>
				
				<plugin>
					<groupId>org.apache.tomcat.mavengroupId>
					<artifactId>tomcat7-maven-pluginartifactId>
					<version>2.2version>
					<configuration>
						
						<port>8080port>
						
						<path>/path>
					configuration>
				plugin>
			plugins>
		pluginManagement>
	build>
project>

2.3 实体类

package org.jaxrs.entity;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "Car")
public class Car {

	private Integer id;
	private String carName;
	private Double price;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getCarName() {
		return carName;
	}
	public void setCarName(String carName) {
		this.carName = carName;
	}
	public Double getPrice() {
		return price;
	}
	public void setPrice(Double price) {
		this.price = price;
	}
	@Override
	public String toString() {
		return "Car [id=" + id + ", carName=" + carName + ", price=" + price + "]";
	}
	public Car(Integer id, String carName, Double price) {
		super();
		this.id = id;
		this.carName = carName;
		this.price = price;
	}
	public Car() {
		super();
	}
	
}

package org.jaxrs.entity;

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

import javax.xml.bind.annotation.XmlRootElement;

/**
 *	基于restful风格的webservice,客户端与服务端之间的通讯可以传递xml数据、json数据
 *	 @XmlRootElement 指定对象序列化为xml或json数据时根节点的名称
 *	xml:
 *		
 *			
 *			
 *			
 *		
 *	json:
 *		{"User":{"id":100,"username":"张三","city":"广东"}}
 *
 */
@XmlRootElement(name = "User")
public class User {
	
	private Integer id;
	private String username;
	private String city;
	
	private List<Car> cars = new ArrayList<Car>();

	
	public User() {
		super();
	}

	public User(Integer id, String username, String city, List<Car> cars) {
		super();
		this.id = id;
		this.username = username;
		this.city = city;
		this.cars = cars;
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getCity() {
		return city;
	}

	public void setCity(String city) {
		this.city = city;
	}

	public List<Car> getCars() {
		return cars;
	}

	public void setCars(List<Car> cars) {
		this.cars = cars;
	}

	@Override
	public String toString() {
		return "User [id=" + id + ", username=" + username + ", city=" + city + ", cars=" + cars + "]";
	}
	
}

2.4 测试不返回

package org.jaxrs.test;

import java.util.List;

import javax.ws.rs.core.MediaType;

import org.apache.cxf.jaxrs.client.WebClient;
import org.jaxrs.entity.User;
import org.junit.Test;


public class Client {

	@Test
	public void testSave() {
		User user = new User(100, "王五", "横沥", null);

		// 通过WebClient对象远程调用服务端
		WebClient.create("http://localhost:8080/ws/userService/userService/user").type(MediaType.APPLICATION_JSON) // 默认请求的数据格式为xml,指定请求的数据格式为json
				.post(user);
	}

2.4.1 控制台打印

客户端

log4j:WARN No appenders could be found for logger (org.apache.cxf.common.logging.LogUtils).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.

服务端

save user:User [id=100, username=王五, city=横沥, cars=[]]

2.5 测试返回单对象

	@Test
	public void testGet() {
		// 通过WebClient对象远程调用服务端
		User user = WebClient.create("http://localhost:8080/ws/userService/userService/user/1")
				.accept(MediaType.APPLICATION_JSON) // 默认响应的数据格式为xml,指定响应的数据格式为json
				.get(User.class);// get(class)返回类型
		System.out.println(user);
	}
2.5.1 控制台打印

客户端
Spring整合ApacheCXF实现基于Restful风格的WebService(基于jaxrs)_第5张图片

服务端

2.6 测试返回集合对象

	@Test
	public void testGetAll() {
		// 通过WebClient对象远程调用服务端
		List<User> user = (List<User>) WebClient.create("http://localhost:8080/ws/userService/userService/user")
				.accept(MediaType.APPLICATION_JSON) // 默认响应的数据格式为xml,指定响应的数据格式为json
				.getCollection(User.class);// get(class)返回类型
		System.out.println(user);
	}
2.6.1 控制台打印

客户端
在这里插入图片描述

服务端

你可能感兴趣的:(WebService,webservice)