客户端调用CXF与spring集成发布的Rest服务

近期,因工作需要,接触到CXF与spring集成发布Rest服务,并实现客户端与服务器端的交互,上网查阅相关资料发现CXF与spring集成发布Rest服务的相关文章较多,但涉及到客户端访问服务器的相关资料确很少,几经周折,整合前人的经验,搭建好此框架之后,觉得有必要记录一下,一方面可以巩固一下流程,另一方面,希望能帮助更多有需要的人!

服务器端的搭建

第一步 Spring 框架环境搭建

1.maven 创建普通 java 工程并调整整体工程环境 

客户端调用CXF与spring集成发布的Rest服务_第1张图片

客户端调用CXF与spring集成发布的Rest服务_第2张图片

 

2.项目目录:

客户端调用CXF与spring集成发布的Rest服务_第3张图片

 

客户端调用CXF与spring集成发布的Rest服务_第4张图片

第二步 配置相关文件

1.添加maven依赖(以下没有用到的可以不添加)


  
  
    junit
    junit
    4.11
    test
  
  
  
    org.springframework
    spring-context-support
    ${spring.version}
  
  
    org.springframework
    spring-web
    ${spring.version}
  
  
    org.springframework
    spring-jdbc
    ${spring.version}
  
  
  
    mysql
    mysql-connector-java
    5.1.38
  
  
    com.alibaba
    druid
    1.0.15
  
  
    org.mybatis
    mybatis
    3.2.8
  
  
    org.mybatis
    mybatis-spring
    1.2.5
  
  
  
    org.slf4j
    slf4j-log4j12
    1.7.26
  
  
  
    org.apache.cxf
    cxf-rt-rs-service-description
    ${cxf.version}
  
  
    org.apache.cxf
    cxf-rt-rs-extension-providers
    ${cxf.version}
  
  
  
    org.codehaus.jackson
    jackson-jaxrs
    1.9.13
  
  
  
    org.aspectj
    aspectjweaver
    1.8.7
  
  
  
    org.apache.commons
    commons-lang3
    3.4
  

2.配置web.xml文件





  
  
    contextConfigLocation
    classpath:spring.xml
  
  
    org.springframework.web.context.ContextLoaderListener
  

  
  
    cxf
    org.apache.cxf.transport.servlet.CXFServlet
  
  
    cxf
    /ws/*
  


第三步、REST服务接口以及实现类

1.在项目目录下新建bean包,在bean文件夹下创建Product类

客户端调用CXF与spring集成发布的Rest服务_第5张图片

package com.spring.rest.bean;

public class Product {
    private long id;
    private String name;
    private int price;

    public Product() {
    }

    public Product(long id, String name, int price) {
        this.id = id;
        this.name = name;
        this.price = price;
    }

    public long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

}

2.在项目目录下新建service包,在service包下新建impl包和inter包,在impl下新建ProductServiceImpl类,在inter包下新建ProductService接口(项目目录如上)

ProductServiceImpl类中内容:

package com.spring.rest.service.impl;

import com.lenovo.rest.bean.Product;
import com.lenovo.rest.service.inter.ProductService;

import java.lang.reflect.Field;
import java.util.*;

public class ProductServiceImpl implements ProductService {
    private static final List productList = new ArrayList();
    static {
        productList.add(new Product(1, "iphone63", 5000));
        productList.add(new Product(2, "ipad mini", 2500));
    }

    @Override
    public List retrieveAllProducts() {

        Collections.sort(productList, new Comparator() {

            @Override
            public int compare(Product p1, Product p2) {
                return (p1.getId() > p2.getId()) ? -1 : 1;
            }
        });
        return productList;
    }

    @Override
    public Product retrieveProductById(long id) {
        Product targetProduct = null;
        for (Product product : productList) {
            if (product.getId() == id) {
                targetProduct = product;
                break;
            }
        }
        return targetProduct;
    }

    @Override
    public List retrieveProductsByName_param(String name){
        List targetList = new ArrayList();
        for (Product product : productList) {
            if (product.getName().equals(name)) {
                targetList.add(product);
            }
        }
        return targetList;
    }
    @Override
    public List retrieveProductsByName_form(String name) {
        List targetList = new ArrayList();
        for (Product product : productList) {
            if (product.getName().equals(name)) {
                targetList.add(product);
            }
        }
        return targetList;
    }

    @Override
    public Product createProduct(Product product) {
        product.setId(new Date().getTime());
        productList.add(product);
        return product;
    }

    @Override
    public Product createProduct(String name,int price){
        Product product = new Product();
        product.setId(new Date().getTime());
        product.setName(name);
        product.setPrice(price);

        productList.add(product);
        return product;
    }

    @Override
    public Product updateProductById(long id, Map fieldMap) {
        Product product = retrieveProductById(id);
        if (product != null) {
            try {
                for (Map.Entry fieldEntry : fieldMap.entrySet()) {
                    Field field = Product.class.getDeclaredField(fieldEntry
                            .getKey());
                    field.setAccessible(true);
                    field.set(product, fieldEntry.getValue());

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return product;
    }

    @Override
    public Product updateProduct(Product product){
        if(product != null){
            Product targetProduct = retrieveProductById(product.getId());
            if(targetProduct != null){
                targetProduct.setName(product.getName());
                targetProduct.setPrice(product.getPrice());
            }

            return targetProduct;
        }

        return null;
    }

    @Override
    public Product updateProduct(long id,String name,int price){
        Product product = retrieveProductById(id);
        if(product != null){
            product.setName(name);
            product.setPrice(price);
        }

        return product;
    }

    @Override
    public Product deleteProductById(long id) {
        Product targetProduct = null;
        Iterator it = productList.iterator();
        while (it.hasNext()) {
            Product product = it.next();
            if (product.getId() == id) {
                targetProduct = product;
                it.remove();
                break;
            }
        }
        return targetProduct;
    }

    @Override
    public Product deleteProductById_param(long id){
        Product targetProduct = null;
        Iterator it = productList.iterator();
        while (it.hasNext()) {
            Product product = it.next();
            if (product.getId() == id) {
                targetProduct = product;
                it.remove();
                break;
            }
        }
        return targetProduct;
    }
}

ProductService接口中的内容:

package com.spring.rest.service.inter;

import com.spring.rest.bean.Product;

import java.util.List;
import java.util.Map;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.FormParam;
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.QueryParam;
import javax.ws.rs.core.MediaType;


public interface ProductService {
    @GET
    @Path("/products")
    @Produces(MediaType.APPLICATION_JSON)
    List retrieveAllProducts();

    @GET
    @Path("/product/{id}")
    @Produces(MediaType.APPLICATION_JSON)
    Product retrieveProductById(@PathParam("id")long id);

    /**
     * 参数查询
     * @param name
     * @return
     */
    @GET
    @Path("/products/name")
    @Produces(MediaType.APPLICATION_JSON)
    List retrieveProductsByName_param(@QueryParam("name")String name);

    /**
     * 提交表单查询
     * @param name
     * @return
     */
    @POST
    @Path("/products/form/name")
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    @Produces(MediaType.APPLICATION_JSON)
    List retrieveProductsByName_form(@FormParam("name")String name);


    @POST
    @Path("/product")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    Product createProduct(Product product);

    @POST
    @Path("/product/create")
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    @Produces(MediaType.APPLICATION_JSON)
    Product createProduct(@FormParam("name")String name,@FormParam("price")int price);

    @PUT
    @Path("/product/{id}")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    Product updateProductById(@PathParam("id")long id,Map fieldMap);

    @PUT
    @Path("/product")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    Product updateProduct(Product product);

    @PUT
    @Path("/product/update")
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    @Produces(MediaType.APPLICATION_JSON)
    Product updateProduct(@FormParam("id")long id,@FormParam("name")String name,@FormParam("price")int price);

    @DELETE
    @Path("/product/{id}")
    @Produces(MediaType.APPLICATION_JSON)
    Product deleteProductById(@PathParam("id")long id);

    @DELETE
    @Path("/product")
    @Produces(MediaType.APPLICATION_JSON)
    Product deleteProductById_param(@QueryParam("id")long id);

}



3.配置xml文件

在main文件下新建resources文件,如下图,点击右上角,将resources文件设置成源文件

客户端调用CXF与spring集成发布的Rest服务_第6张图片

在resources文件下新建spring.xml和spring-cxf.xml

 

spring.xml文件配置





    
    





spring-cxf.xml文件配置





    
        
            
        
        
            
        
    




 

第四步,调用REST服务

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>



    
    Demo
    
    
    
    
    




Product List

第五步,发布并访问

1.配置tomcat及端口(pom.xml)


  
    
      org.apache.tomcat.maven
      tomcat7-maven-plugin
      2.2
      
        8080
        /springCxfREST
        UTF-8
        tomcat7
      
    
  

2.将打包的压缩文件设置为.war文件

在pom.xml文件中加入war

如下:

com.spring.REST
REST
1.0-SNAPSHOT
war

3.点击右上角,Maven下的install开始打包

客户端调用CXF与spring集成发布的Rest服务_第7张图片

 打包成功后开始运行

客户端调用CXF与spring集成发布的Rest服务_第8张图片

 

客户端搭建

重新搭建一个spring框架,环境搭建和服务器端一样

1.项目目录:

客户端调用CXF与spring集成发布的Rest服务_第9张图片

 

2.配置pom.xml



  org.apache.cxf
  cxf-rt-rs-service-description
  ${cxf.version}


  org.apache.cxf
  cxf-rt-rs-client
  ${cxf.version}



  org.codehaus.jackson
  jackson-jaxrs
  1.9.13

3.将服务器端Product类和ProductService接口复制过来

新建WebClientTest类

package com.spring.rest.client;

import org.apache.cxf.jaxrs.client.JAXRSClientFactory;
import org.codehaus.jackson.jaxrs.JacksonJsonProvider;

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

public class JAXRSClient {

    public static void main(String[] args) {
        JacksonJsonProvider jsonProvider = new JacksonJsonProvider();
        List providerList = new ArrayList();
        providerList.add(jsonProvider);
        ProductService us = JAXRSClientFactory.create("http://localhost:8080/springCxfREST/ws/rest",ProductService.class,providerList);
        List products = us.retrieveAllProducts();
        System.out.println(products.size());
        Product product = us.retrieveProductById(1);
        System.out.println(product.toString());

    }

} 
  

启动服务器端,运行客户端main方法

运行结果

客户端调用CXF与spring集成发布的Rest服务_第10张图片

 

你可能感兴趣的:(客户端调用CXF与spring集成发布的Rest服务)