Spring实现CXF服务端

上篇博客简单介绍了Restful Service的服务端编程,本篇博客详细的介绍了通过Spring集成发布服务的过程。


一、实现工具: Eclipse

二、实现过程及代码:

          1、使用Maven创建web项目cxf-rs-spring

  File -> New -> Others -> Maven -> Maven Project -> use default ... -> maven archetype webapp  


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.0</modelVersion>
  <groupId>me.cxf-sample</groupId>
  <artifactId>cxf-rs-spring</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>cxf-rs-spring Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <!-- 申明常用软件的版本 -->
	<properties>
	        <jettyVersion>9.3.7.v20160115</jettyVersion>
	        <cxf.version>3.1.6</cxf.version>
	</properties>
	
	<dependencies>
	        <dependency>
	          <groupId>junit</groupId>
	          <artifactId>junit</artifactId>
	          <version>3.8.1</version>
	          <scope>test</scope>
	        </dependency>
	
	        <dependency>
	                <groupId>javax.ws.rs</groupId>
	                <artifactId>javax.ws.rs-api</artifactId>
	                <version>2.0.1</version>
	        </dependency>
	
	        <!-- CXF jaxrs 依赖 -->
	        <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>
	
	        <!-- CXF jaxrs description 依赖 -->
	        <dependency>
	          <groupId>org.apache.cxf</groupId>
	          <artifactId>cxf-rt-rs-service-description</artifactId>
	          <version>${cxf.version}</version>
	        </dependency>
	
	        <!-- spring 依赖 -->
	        <dependency>
	          <groupId>org.springframework</groupId>
	          <artifactId>spring-web</artifactId>
	          <version>3.2.8.RELEASE</version>
	        </dependency>
			
			<!-- Json 依赖 -->
			<dependency>
		        <groupId>org.codehaus.jackson</groupId>
		        <artifactId>jackson-jaxrs</artifactId>
		        <version>1.9.13</version>
			</dependency>
			<dependency>
			    <groupId>org.codehaus.jackson</groupId>
			    <artifactId>jackson-xc</artifactId>
			    <version>1.9.13</version>
			</dependency>
			
			<dependency>
				<groupId>org.slf4j</groupId>
				<artifactId>slf4j-jdk14</artifactId>
				<version>1.7.19</version>
			</dependency>
			<dependency>
				<groupId>org.slf4j</groupId>
				<artifactId>jcl-over-slf4j</artifactId>
				<version>1.7.19</version>
			</dependency>
			
	</dependencies>
	<build>
	        <finalName>cxf-rs-spring</finalName>
	        <!-- jetty:run 插件 -->
	        <plugins>
	          <plugin>
	                <groupId>org.eclipse.jetty</groupId>
	                <artifactId>jetty-maven-plugin</artifactId>
	                <version>${jettyVersion}</version>
	          </plugin>
	        </plugins>
	</build>
</project>

3、找到文件/src/main/webapp/WEB-INF/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>cxf-rs-spring Maven Webapp</display-name>

  <!-- 设置Spring容器加载配置文件路径 -->
  <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>WEB-INF/beans.xml</param-value>
  </context-param>
  <!-- 加载Spring容器配置 -->
  <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <listener>
        <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
  </listener>

  <!-- 加载CXFServlet容器配置 -->
  <servlet>
        <servlet-name>CXFServlet</servlet-name>
        <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
  </servlet>
  <servlet-mapping>
        <servlet-name>CXFServlet</servlet-name>
        <url-pattern>/*</url-pattern>
  </servlet-mapping>

</web-app>

4、在相同目录下(/src/main/webapp/WEB-INF/),新建beans.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="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/jaxrs
        http://cxf.apache.org/schemas/jaxrs.xsd">

  <!-- do not use import statements if CXFServlet init parameters link to this beans.xml -->

  <import resource="classpath:META-INF/cxf/cxf.xml" />
  <import resource="classpath:META-INF/cxf/cxf-servlet.xml" />

  <jaxrs:server id="customerService" address="/service1">
        <jaxrs:serviceBeans>
                <ref bean="customerBean" />
        </jaxrs:serviceBeans>
        <!-- 引入json 输入/输出支持 -->
        <jaxrs:providers>
                <bean class="org.codehaus.jackson.jaxrs.JacksonJaxbJsonProvider"/>
                <bean class="org.apache.cxf.jaxrs.provider.JAXBElementProvider"/>
        </jaxrs:providers>
  </jaxrs:server>

  <bean id="customerBean" class="demo.jaxrs.server.CustomerService" />

</beans>
 
5、在/src.java/main/ 目录下 编写服务端代码 

创建项目,这时发现没有 src/main/java 源代码目录。 按以下步骤操作:

项目名 -> Context Menu(鼠标右键) -> properties -> Java Build Path -> JRE System Lib -> Edit按钮 -> Workspace default JRE

根资源类(CustomerService):

/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package demo.jaxrs.server;

import java.util.HashMap;
import java.util.Map;

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.Response;

@Path("/customerservice/")
//@Produces("text/xml")
//@Produces("application/json")
@Produces({ "text/plain","text/xml", "application/json", "application/xml", "application/x-www-form-urlencoded"})
@Consumes({ "application/x-www-form-urlencoded", "text/plain","text/xml", "application/json" })
public class CustomerService {
    long currentId = 123;
    Map<Long, Customer> customers = new HashMap<Long, Customer>();
    Map<Long, Order> orders = new HashMap<Long, Order>();

    public CustomerService() {
        init();
    }

    @GET
    @Path("/customers/{id}/")
    public Customer getCustomer(@PathParam("id") String id) {
        System.out.println("----invoking getCustomer, Customer id is: " + id);
        long idNumber = Long.parseLong(id);
        Customer c = customers.get(idNumber);
        return c;
    }

    @PUT
    @Path("/customers/")
    public Response updateCustomer(Customer customer) {
        System.out.println("----invoking updateCustomer, Customer name is: " + customer.getName());
        Customer c = customers.get(customer.getId());
        Response r;
        if (c != null) {
            customers.put(customer.getId(), customer);
            r = Response.ok().build();
        } else {
            r = Response.notModified().build();
        }

        return r;
    }

    @POST
    @Path("/customers/")
    public Response addCustomer(Customer customer) {
        System.out.println("----invoking addCustomer, Customer name is: " + customer.getName());
        customer.setId(++currentId);

        customers.put(customer.getId(), customer);

        return Response.ok(customer).build();
    }

    @DELETE
    @Path("/customers/{id}/")
    public Response deleteCustomer(@PathParam("id") String id) {
        System.out.println("----invoking deleteCustomer, Customer id is: " + id);
        long idNumber = Long.parseLong(id);
        Customer c = customers.get(idNumber);

        Response r;
        if (c != null) {
            r = Response.ok().build();
            customers.remove(idNumber);
        } else {
            r = Response.notModified().build();
        }

        return r;
    }

    @Path("/orders/{orderId}/")
    public Order getOrder(@PathParam("orderId") String orderId) {
        System.out.println("----invoking getOrder, Order id is: " + orderId);
        long idNumber = Long.parseLong(orderId);
        Order c = orders.get(idNumber);
        return c;
    }

    final void init() {
        Customer c = new Customer();
        c.setName("John");
        c.setId(123);
        customers.put(c.getId(), c);

        Order o = new Order();
        o.setDescription("order 223");
        o.setId(223);
        orders.put(o.getId(), o);
    }

}

子资源类:

Order类:

/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package demo.jaxrs.server;

import java.util.HashMap;
import java.util.Map;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "Order")
public class Order {
    private long id;
    private String description;
    private Map<Long, Product> products = new HashMap<Long, Product>();

    public Order() {
        init();
    }

    public long getId() {
        return id;
    }

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

    public String getDescription() {
        return description;
    }

    public void setDescription(String d) {
        this.description = d;
    }

    @GET
    @Path("products/{productId}/")
    public Product getProduct(@PathParam("productId")int productId) {
        System.out.println("----invoking getProduct with id: " + productId);
        Product p = products.get(new Long(productId));
        return p;
    }

    final void init() {
        Product p = new Product();
        p.setId(323);
        p.setDescription("product 323");
        products.put(p.getId(), p);
    }
}

Produce类:

/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package demo.jaxrs.server;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "Product")
public class Product {
    private long id;
    private String description;

    public long getId() {
        return id;
    }

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

    public String getDescription() {
        return description;
    }

    public void setDescription(String d) {
        this.description = d;
    }
}

最后文件目录结构为



6、运行项目

Maven运行参数为 package jetty:run


7、 运行结果:

GET 请求

POST请求

8、 如果要输出JSON格式的文本,需要在pom.xml 和beans.xml中添加依赖, 上述代码中已添加,可自行查看

运行结果如下:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值