Spring4 + cxf3 构建restful webservice

本文介绍通过spring4.0.2 + apache cxf3.0.3构建一个restful webservice服务。

项目的结构如下:

jaxrs-client:客户端
jaxrs-interface:公共接口
jaxrs-server:服务端
说明:客户端与服务端均使用公共接口中的定义

1、新建一个maven项目jaxrs-interface

其中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.0</modelVersion>
	<groupId>com.hode</groupId>
	<artifactId>jaxrs-interface</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<properties>
		<cxf.version>3.0.3</cxf.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.apache.cxf</groupId>
			<artifactId>cxf-rt-transports-http</artifactId>
			<version>${cxf.version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.cxf</groupId>
			<artifactId>cxf-rt-frontend-jaxrs</artifactId>
			<version>${cxf.version}</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.1</version>
				<configuration>
					<source>1.7</source>
					<target>1.7</target>
					<encoding>UTF-8</encoding>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

编写一个接口RestUserService.java及一个对象类User.java,代码如下

package com.hode.rest.service;

import java.util.Date;

import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;

import com.hode.rest.model.User;

@Path("/restUserService")
public interface RestUserService {

	@GET
	@Path("/getDate")
	public Date getDate();
	
	@POST
	@Path("/getUserById")
	public User getUserById(Integer id);
	
	@POST
	@Path("/getUserByUsername")
	public User getUserByUsername(String username);
	
	@POST
	@Path("/saveUser")
	public Integer saveUser(User user);

}
package com.hode.rest.model;

import java.util.Date;

public class User {

	private Integer id;
	
	private String username;
	
	private String remark;
	
	private Date createTime;
	
	private Date updateTime;

	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 getRemark() {
		return remark;
	}

	public void setRemark(String remark) {
		this.remark = remark;
	}

	public Date getCreateTime() {
		return createTime;
	}

	public void setCreateTime(Date createTime) {
		this.createTime = createTime;
	}

	public Date getUpdateTime() {
		return updateTime;
	}

	public void setUpdateTime(Date updateTime) {
		this.updateTime = updateTime;
	}
	
}

interface层编写完毕。

2、新建一个服务端项目,此服务端使用jetty作为server

pom.xml如下,注意其中依赖了jaxrs-interface,实际上服务端是实现了interface中定义的接口逻辑。

<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.0</modelVersion>
	<groupId>com.hode</groupId>
	<artifactId>jaxrs-server</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	
	<properties>
		<jaxrs-interface.version>0.0.1-SNAPSHOT</jaxrs-interface.version>
		<spring.version>4.0.2.RELEASE</spring.version>
		<log4j.version>1.2.17</log4j.version>
		<junit.version>4.11</junit.version>
	</properties>
	
	<dependencies>
		
		<dependency>
			<groupId>com.hode</groupId>
			<artifactId>jaxrs-interface</artifactId>
			<version>${jaxrs-interface.version}</version>
		</dependency>
		
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context-support</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>${spring.version}</version>
		</dependency>
		
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${spring.version}</version>
			<scope>test</scope>
		</dependency>
		
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>${junit.version}</version>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>${log4j.version}</version>
		</dependency>
		
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>1.6.1</version>
		</dependency>
		
		<dependency>
			<groupId>com.fasterxml.jackson.jaxrs</groupId>
			<artifactId>jackson-jaxrs-json-provider</artifactId>
			<version>2.5.1</version>
		</dependency>
		
		
		
		<dependency>
			<groupId>org.eclipse.jetty</groupId>
			<artifactId>jetty-server</artifactId>
			<version>8.0.0.M3</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>org.eclipse.jetty</groupId>
			<artifactId>jetty-webapp</artifactId>
			<version>8.0.0.M3</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>org.eclipse.jetty</groupId>
			<artifactId>jetty-servlet</artifactId>
			<version>8.0.0.M3</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>org.eclipse.jetty</groupId>
			<artifactId>jetty-io</artifactId>
			<version>8.0.0.M3</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>org.eclipse.jetty</groupId>
			<artifactId>jetty-util</artifactId>
			<version>8.0.0.M3</version>
			<scope>provided</scope>
		</dependency>
		
		<dependency>
			<groupId>org.mortbay.jetty</groupId>
			<artifactId>jsp-2.1-glassfish</artifactId>
			<version>2.1.v20100127</version>
			<scope>provided</scope>
		</dependency>
		
		
	</dependencies>
	
	
	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.1</version>
				<configuration>
					<source>1.7</source>
					<target>1.7</target>
					<encoding>UTF-8</encoding>
				</configuration>
			</plugin>
			
			<plugin>
				<artifactId>maven-war-plugin</artifactId>
				<configuration>
					<version>3.0</version>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

编写一个实现类,实现接口功能,定义为RestUserServiceImpl.java,代码如下

package com.hode.rest.service.impl;

import java.util.Date;
import java.util.Random;

import org.apache.log4j.Logger;

import com.hode.rest.model.User;
import com.hode.rest.service.RestUserService;

public class RestUserServiceImpl implements RestUserService {

	private Logger log = Logger.getLogger(getClass());
	
	@Override
	public Date getDate() {
		return new Date();
	}
	
	@Override
	public User getUserById(Integer id) {
		log.info(id);
		User user = new User();
		user.setUsername("test-"+this);
		user.setId(new Random().nextInt());
		user.setRemark("test-[测试]"+this);
		user.setCreateTime(new Date());
		user.setUpdateTime(new Date());
		return user;
	}

	@Override
	public User getUserByUsername(String username) {
		log.info(username);
		User user = new User();
		user.setUsername("test-"+this);
		user.setId(new Random().nextInt());
		user.setRemark("test-"+this);
		user.setCreateTime(new Date());
		user.setUpdateTime(new Date());
		return user;
	}

	@Override
	public Integer saveUser(User user) {
		log.info(user.getId());
		log.info(user.getCreateTime());
		log.info(user.getRemark());
		return 0;
	}

}

再编写spring配置文件applicationContext.xml,log4j.properties,JettyServer.java文件,代码依次如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:jaxrs="http://cxf.apache.org/jaxrs" xmlns:cxf="http://cxf.apache.org/core"
	xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd  
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd
        http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd
        http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd">
	
	<import resource="classpath:META-INF/cxf/cxf.xml" />
	<import resource="classpath:META-INF/cxf/cxf-servlet.xml" />
	
	<bean id="loggingInInterceptor" class="org.apache.cxf.interceptor.LoggingInInterceptor" />
	
	<bean id="loggingOutInterceptor" class="org.apache.cxf.interceptor.LoggingOutInterceptor" />
	
	<cxf:bus>
		<cxf:inInterceptors>
			<ref bean="loggingInInterceptor" />
		</cxf:inInterceptors>
		<cxf:outInterceptors>
			<ref bean="loggingOutInterceptor" />
		</cxf:outInterceptors>
	</cxf:bus>
	
	<jaxrs:server id="restUserService" address="/">
		<jaxrs:serviceBeans>
			<bean class="com.hode.rest.service.impl.RestUserServiceImpl" />
		</jaxrs:serviceBeans>
		<jaxrs:providers>
			<ref bean="jackson"/>
			<ref bean="jaxb"/>
		</jaxrs:providers>
		<jaxrs:extensionMappings>
			<entry key="json" value="application/json;charset=UTF-8"/>
			<entry key="xml" value="application/xml;charset=UTF-8"/>
		</jaxrs:extensionMappings>
	</jaxrs:server>
	
	<bean id="jackson" class="com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider"/>
	
    <bean id="jaxb" class="org.apache.cxf.jaxrs.provider.JAXBElementProvider">
        <property name="unmarshallAsJaxbElement" value="true"/>
        <property name="marshallAsJaxbElement" value="true"/>
    </bean>
	
</beans>

log4j.rootLogger=INFO,Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n

log4j.logger.com.hode=DEBUG
package com.hode;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.WebAppContext;


public class JettyServer {

	public static void main(String[] args) throws Exception{
		Server server = new Server(80);
		WebAppContext context = new WebAppContext();  
        context.setContextPath("/");  
        context.setWar("src/main/webapp");  
        server.setHandler(context);  
        server.start();  
        server.join();
	}

}

最后在目录webapp/WEB-INF中编写web.xml,代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	id="WebApp_ID" version="3.0">
	
	<display-name>jaxrs-server</display-name>
	
	<servlet>
		<servlet-name>CXFService</servlet-name>
		<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
		<init-param>
			<param-name>config-location</param-name>
			<param-value>classpath:applicationContext.xml</param-value>
		</init-param>
	</servlet>

	<servlet-mapping>
		<servlet-name>CXFService</servlet-name>
		<url-pattern>/rs/*</url-pattern>
	</servlet-mapping>
	
	
</web-app>

3、新建一个客户端项目,完成测试

编写pom.xml,可以看到client端同样是依赖了interface项目,代码如下:

<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.0</modelVersion>
	<groupId>com.hode</groupId>
	<artifactId>jaxrs-client</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<properties>
		<spring.version>4.0.2.RELEASE</spring.version>
		<log4j.version>1.2.16</log4j.version>
		<junit.version>4.11</junit.version>
		<cxf.version>3.0.3</cxf.version>
	</properties>

	<dependencies>
	
		<dependency>
			<groupId>com.hode</groupId>
			<artifactId>jaxrs-interface</artifactId>
			<version>0.0.1-SNAPSHOT</version>
		</dependency>
		
		<dependency>
			<groupId>org.apache.cxf</groupId>
			<artifactId>cxf-rt-rs-client</artifactId>
			<version>${cxf.version}</version>
		</dependency>
		
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context-support</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>${log4j.version}</version>
		</dependency>
		
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>1.6.1</version>
		</dependency>

		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>${junit.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-mapper-asl</artifactId>
			<version>1.9.13</version>
		</dependency>

		<dependency>
			<groupId>com.fasterxml.jackson.jaxrs</groupId>
			<artifactId>jackson-jaxrs-json-provider</artifactId>
			<version>2.5.1</version>
		</dependency>

		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-core-asl</artifactId>
			<version>1.9.13</version>
		</dependency>

	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.1</version>
				<configuration>
					<source>1.7</source>
					<target>1.7</target>
					<encoding>UTF-8</encoding>
				</configuration>
			</plugin>
		</plugins>
	</build>

</project>

编写2个测试类分别测试两种协议格式json和xml,测试类如下:

package com.hode;


import org.apache.log4j.Logger;

public class BaseTest {

	protected Logger log = Logger.getLogger(getClass());
	
}

package com.hode;

import java.util.Date;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.hode.rest.model.User;
import com.hode.rest.service.RestUserService;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath*:applicationContext-json.xml"})
public class JAXRSClientJsonTest extends BaseTest {
	
	@Autowired
	private RestUserService restUserService;
	
	private User user = null;
	
	@Test
	public void getDate(){
		Date date = restUserService.getDate();
		log.info(date);
	}
	
	@Test
	public void getUserById(){
		user = restUserService.getUserById(new Integer(1));
		log.info(user.getId());
		log.info(user.getCreateTime());
		log.info(user.getRemark());
	}
	
	@Test
	public void getUserByUsername(){
		user = restUserService.getUserByUsername("test");
		log.info(user.getId());
		log.info(user.getCreateTime());
		
	}
	@Test
	public void saveUser(){
		user = new User();
		user.setRemark(user.getRemark()+"[测试用]");
		int result = restUserService.saveUser(user);
		log.info(result);
		
	}

}

package com.hode;

import java.util.Date;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.hode.rest.model.User;
import com.hode.rest.service.RestUserService;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath*:applicationContext-xml.xml"})
public class JAXRSClientXmlTest extends BaseTest {
	
	@Autowired
	private RestUserService restUserService;
	
	private User user = null;
	
	@Test
	public void getDate(){
		Date date = restUserService.getDate();
		log.info(date);
	}
	
	@Test
	public void getUserById(){
		user = restUserService.getUserById(new Integer(1));
		log.info(user.getId());
		log.info(user.getCreateTime());
		log.info(user.getRemark());
	}
	
	@Test
	public void getUserByUsername(){
		user = restUserService.getUserByUsername("test");
		log.info(user.getId());
		log.info(user.getCreateTime());
		
	}
	@Test
	public void saveUser(){
		user = new User();
		user.setRemark(user.getRemark()+"[测试用]");
		int result = restUserService.saveUser(user);
		log.info(result);
		
	}

}


再编写两个spring配置文件applicationContext-json.xml,applicationContext-xml.xml及log4j.properties文件

applicationContext-json.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:jaxrs-client="http://cxf.apache.org/jaxrs-client"
	xmlns:cxf="http://cxf.apache.org/core"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd
        http://cxf.apache.org/jaxrs-client http://cxf.apache.org/schemas/jaxrs-client.xsd ">

	<bean id="loggingInInterceptor" class="org.apache.cxf.interceptor.LoggingInInterceptor" />
	
	<bean id="loggingOutInterceptor" class="org.apache.cxf.interceptor.LoggingOutInterceptor" />

	<cxf:bus>
		<cxf:inInterceptors>
			<ref bean="loggingInInterceptor" />
		</cxf:inInterceptors>
		<cxf:outInterceptors>
			<ref bean="loggingOutInterceptor" />
		</cxf:outInterceptors>
	</cxf:bus>
	
	<jaxrs-client:client id="restUserService" serviceClass="com.hode.rest.service.RestUserService" address="http://localhost/rs">
		<jaxrs-client:providers>
			<ref bean="jaxb"/>
			<ref bean="jackson"/>
		</jaxrs-client:providers>
		<jaxrs-client:headers>
		<!--  
			<entry key="Accept" value="application/xml;charset=UTF-8" />
			<entry key="Content-Type" value="application/xml;charset=UTF-8" />
		
			<entry key="Accept" value="application/json;charset=UTF-8" />
			<entry key="Content-Type" value="application/json;charset=UTF-8" />
		-->
			<entry key="Accept" value="application/json;charset=UTF-8" />
			<entry key="Content-Type" value="application/json;charset=UTF-8" />
		</jaxrs-client:headers>
	</jaxrs-client:client>
	
	<bean id="jackson" class="com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider"/>
	
	<bean id="jaxb" class="org.apache.cxf.jaxrs.provider.JAXBElementProvider">
        <property name="unmarshallAsJaxbElement" value="true"/>
        <property name="marshallAsJaxbElement" value="true"/>
    </bean>

</beans>

applicationContext-xml.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:jaxrs-client="http://cxf.apache.org/jaxrs-client"
	xmlns:cxf="http://cxf.apache.org/core"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd
        http://cxf.apache.org/jaxrs-client http://cxf.apache.org/schemas/jaxrs-client.xsd ">

	<bean id="loggingInInterceptor" class="org.apache.cxf.interceptor.LoggingInInterceptor" />
	
	<bean id="loggingOutInterceptor" class="org.apache.cxf.interceptor.LoggingOutInterceptor" />

	<cxf:bus>
		<cxf:inInterceptors>
			<ref bean="loggingInInterceptor" />
		</cxf:inInterceptors>
		<cxf:outInterceptors>
			<ref bean="loggingOutInterceptor" />
		</cxf:outInterceptors>
	</cxf:bus>
	
	<jaxrs-client:client id="restUserService" serviceClass="com.hode.rest.service.RestUserService" address="http://localhost/rs">
		<jaxrs-client:providers>
			<ref bean="jaxb"/>
			<ref bean="jackson"/>
		</jaxrs-client:providers>
		<jaxrs-client:headers>
		<!--  
			<entry key="Accept" value="application/xml;charset=UTF-8" />
			<entry key="Content-Type" value="application/xml;charset=UTF-8" />
		
			<entry key="Accept" value="application/json;charset=UTF-8" />
			<entry key="Content-Type" value="application/json;charset=UTF-8" />
		-->
			<entry key="Accept" value="application/xml;charset=UTF-8" />
			<entry key="Content-Type" value="application/xml;charset=UTF-8" />
		</jaxrs-client:headers>
	</jaxrs-client:client>
	
	<bean id="jackson" class="com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider"/>
	
	<bean id="jaxb" class="org.apache.cxf.jaxrs.provider.JAXBElementProvider">
        <property name="unmarshallAsJaxbElement" value="true"/>
        <property name="marshallAsJaxbElement" value="true"/>
    </bean>

</beans>

log4j.properties文件可参考上面的写法。

4、完成编写后,执行测试

先运行JettyServer.java中的main方法,启动服务端,再分别运行测试类JAXRSClientJsonTest.java及JAXRSClientXmlTest.java截取部分日志如下

----------------------------
ID: 2
Address: http://localhost/rs/restUserService/getUserByUsername
Encoding: UTF-8
Http-Method: POST
Content-Type: application/json;charset=UTF-8
Headers: {Accept=[application/json;charset=UTF-8], Cache-Control=[no-cache], connection=[keep-alive], Content-Length=[4], content-type=[application/json;charset=UTF-8], Host=[localhost], Pragma=[no-cache], User-Agent=[Apache CXF 3.0.3]}
Payload: test
--------------------------------------
9060 [qtp1604125387-21] INFO  com.hode.rest.service.impl.RestUserServiceImpl  - test
9081 [qtp1604125387-21] INFO  org.apache.cxf.interceptor.LoggingOutInterceptor  - Outbound Message
---------------------------
ID: 2
Response-Code: 200
Content-Type: application/json;charset=UTF-8
Headers: {Content-Type=[application/json;charset=UTF-8], Date=[]}
Payload: {"id":-379018143,"username":"test-com.hode.rest.service.impl.RestUserServiceImpl@333f74eb","remark":"test-com.hode.rest.service.impl.RestUserServiceImpl@333f74eb"}
--------------------------------------
9116 [qtp1604125387-18] INFO  org.apache.cxf.interceptor.LoggingInInterceptor  - Inbound Message
----------------------------
----------------------------
ID: 6
Address: http://localhost/rs/restUserService/getUserByUsername
Encoding: UTF-8
Http-Method: POST
Content-Type: application/xml;charset=UTF-8
Headers: {Accept=[application/xml;charset=UTF-8], Cache-Control=[no-cache], connection=[keep-alive], Content-Length=[76], content-type=[application/xml;charset=UTF-8], Host=[localhost], Pragma=[no-cache], User-Agent=[Apache CXF 3.0.3]}
Payload: <?xml version="1.0" encoding="UTF-8" standalone="yes"?><String>test</String>
--------------------------------------
12548 [qtp1604125387-21] INFO  com.hode.rest.service.impl.RestUserServiceImpl  - test
12551 [qtp1604125387-21] INFO  org.apache.cxf.interceptor.LoggingOutInterceptor  - Outbound Message
---------------------------
ID: 6
Response-Code: 200
Content-Type: application/xml;charset=UTF-8
Headers: {Content-Type=[application/xml;charset=UTF-8], Date=[]}
Payload: <?xml version="1.0" encoding="UTF-8" standalone="yes"?><User><createTime>2016-01-11T14:50:33.691+08:00</createTime><id>1033027991</id><remark>test-com.hode.rest.service.impl.RestUserServiceImpl@333f74eb</remark><updateTime>2016-01-11T14:50:33.691+08:00</updateTime><username>test-com.hode.rest.service.impl.RestUserServiceImpl@333f74eb</username></User>
--------------------------------------
12563 [qtp1604125387-18] INFO  org.apache.cxf.interceptor.LoggingInInterceptor  - Inbound Message
----------------------------

Demo代码下载

结束。


赞赏(Donation)
微信(Wechat Pay)

donation-wechatpay