REST+SPRING+webservice交互xml数据

第一步:首先配置rest+spring环境

添加Rest  四个依赖库

选择项目---MyEclipse-->Add REST Web Service Capablities

                                       

   

选择添加  Add  REST  Capabilities ----->选择下图 四个依赖库

                                       l

第二步: 添加   jersey-spring-1.5.jar 



第三步:在web.xml里加入以下代码


Xml代码   
   

  JAX-RS REST Servlet
      JAX-RS REST Servlet
      
          com.sun.jersey.spi.container.servlet.ServletContainer
      

      1
  
  
      JAX-RS REST Servlet
      /services/*
  

 
 Struts2
    org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
  
  
    Struts2

    *.action
      *.jsp
  

注意:这里给出struts2的配置,是因为怕将所有url拦截         导致接下来测webservice出错

第四步:client

package com.xxyd.iap_service_monitor.testrest;

import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.Calendar;

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

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.xmlbeans.XmlException;

import sample.xmlbean.CustomersDocument;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.core.util.MultivaluedMapImpl;

public class RestWebserviceClient {
    private static final String URL = "http://localhost:8080/iapServiceMonitor/services/test/handleTest";

    public static void main(String[] args) throws HttpException, IOException {

        
        /**  测试  post字符串
         Client client = Client.create();
         WebResource resource = client.resource(URL);
         MultivaluedMap params = new MultivaluedMapImpl();
         params.add("params", "felix");
        
         ClientResponse response =
         resource.queryParams(params).post(ClientResponse.class);
         String ret = response.getEntity(String.class);
         // System.out.println(ret);
         System.out.println(ret);
**/
        
        
        //测试post xml文件
        File xmlFile = new File("c://build//customers.xml");
        try {
            CustomersDocument doc = CustomersDocument.Factory.parse(xmlFile);
            String response = Client.create().resource(URL)
                    .type(MediaType.APPLICATION_XML)
                    .post(String.class, doc.toString());
            System.out.println("client返回值=" + response);
        } catch (XmlException e) {
            // TODO Auto-generated catch block
            System.out.println("读取xml文件出错");
        }

    }
}


第五步:server

package com.xxyd.iap_service_monitor.testrest;


 
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;   
import javax.ws.rs.POST;
import javax.ws.rs.Path;   
import javax.ws.rs.Produces;   
import javax.ws.rs.QueryParam;   
import javax.ws.rs.core.MediaType;

import org.apache.xmlbeans.XmlException;


@Produces({ "application/xml", "application/json" })
@Consumes({ "application/xml", "application/json" })
@Path("test")   
public class RestWebserviceServer {
    
    
    
        //外部传过来的参数  

        @Produces({ "application/xml", "application/json" })
        @Consumes({ "application/xml", "application/json" })   
        @POST  
        @Path("aaa")
        public String helloWorld(  @QueryParam("params") String userId) {   
            String ret = "Hello World!"+userId;   
            return ret;   
        }   
           
        // 子路径  
        @Path("getUsers")      
        @GET  
        @Produces({ "application/xml", "application/json" })
        @Consumes({ "application/xml", "application/json" })      
        public String getUsers() {   
           
            return "hello felix";   
        }   
     // 用于测试的方法
        @Produces({ "application/xml", "application/json" })
        @Consumes({ "application/xml", "application/json" })
        @Path("handleTest")
        @POST
        public String handleTest(String xmlDoc) {

            CustomerXMLBean xmlBean =new CustomerXMLBean();
            xmlBean.customerReader(xmlDoc);
            return "hello";
            
        }
    }  
    
    
第六步:      CustomerXMLBean    读写xml工具类
package com.xxyd.iap_service_monitor.testrest;

import java.io.File;

import sample.xmlbean.*;
import org.apache.xmlbeans.XmlOptions;

public class CustomerXMLBean {
    private String filename = null;

    public CustomerXMLBean(String filename) {
        super();
        this.filename = filename;
    }
    public CustomerXMLBean() {
        
    }
    public  void customerReader(String xmlFile) {
        try {
            System.out.println("client ×××××××××××"+xmlFile);
            //File xmlFile = new File(filename);
            CustomersDocument doc = CustomersDocument.Factory.parse(xmlFile);
            CustomerType[] customers = doc.getCustomers().getCustomerArray();

            for (int i = 0; i < customers.length; i++) {
                CustomerType customer = customers[i];
                System.out.println("Customer#" + i);
                System.out.println("Customer ID:" + customer.getId());
                System.out.println("First name:" + customer.getFirstname());
                System.out.println("Last name:" + customer.getLastname());
                System.out.println("Gender:" + customer.getGender());
                System.out.println("PhoneNumber:" + customer.getPhoneNumber());
                // Primary address
                PrimaryAddressType primaryAddress = customer.getAddress()
                        .getPrimaryAddress();
                System.out.println("PrimaryAddress:");
                System.out.println("PostalCode:" + primaryAddress.getPostalCode());
                System.out.println("AddressLine1:" + primaryAddress.getAddressLine1());
                System.out.println("AddressLine2:" + primaryAddress.getAddressLine2());
                // Billing address
                BillingAddressType billingAddress = customer.getAddress()
                        .getBillingAddress();
                System.out.println("BillingAddress:");
                System.out.println("Receiver:" + billingAddress.getReceiver());
                System.out.println("PostalCode:" + billingAddress.getPostalCode());
                System.out.println("AddressLine1:" + billingAddress.getAddressLine1());
                System.out.println("AddressLine2:" + billingAddress.getAddressLine2());

            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
 }


第七步:c://build//customers.xml   文件

  
      
          
                1  
                female  
                Jessica  
                Lim  
                1234567  
                

  
                      
                            350106  
                            #25-1  
                            SHINSAYAMA 2-CHOME  
                    
  
                      
                            Ms Danielle  
                            350107  
                            #167  
                            NORTH TOWER HARBOUR CITY  
                    
  
                
  
          
          
                2  
                male  
                David  
                Bill  
                808182  
                
  
                      
                            319087  
                            1033 WS St.  
                            Tima Road  
                    
  
                      
                            Mr William  
                            672993  
                            1033 WS St.  
                            Tima Road  
                    
  
                
  
        
  
     

第八步:下载  xmlbeans-2.5.0 解析xml的工具  

解压放在 D:\xmlbeans-2.5.0      该文件中的  D:\xmlbeans-2.5.0\bin/scomp.cmd  将被  第九步用于生成   ×××xml.jar文件
 操作:解压后将   lib下  所有jar包  拷到 工程的  lib 目录下



第九步:  将  customers.xml 的     customerXmlBean.jar 拷到  工程lib包下

1,通过customer.xml先 生成customer.xsd  和 customer.xsdconfig文件放在c:/build
2,在本文,我是这样运行的:首先使用cmd进入D:\Program Files\Java\jdk1.7.0_04\bin,然后运行下面的命令:

      D:\Program Files\Java\jdk1.7.0_04\bin>D:\xmlbeans-2.5.0\bin/scomp.cmd -src c:/build/src  -out c:/build/customerXmlBean.jar
c:/build/customer.xsd  -compiler javac c:/build/customer.xsdconfig
3.,这样就生成了   c:/build/customerXmlBean.jar    将这个jar包  拷到    工程   lib包下


整体测试操作:
第一步到第三步是配置rest+spring环境,第六步到第九步是为 测试  post    xml文件,而为生成xml文件及解析xml文件做准备,最主要的就是  第四步 和第五步

所有准备工作做完之后,将项目运行起来,执行第四步,则会输出相应的值。
项目控制台预期输出:
Customer#0
Customer ID:3
First name:Jessica
Last name:Lim
Gender:female
PhoneNumber:1234567
PrimaryAddress:
PostalCode:350106
AddressLine1:#25-1
AddressLine2:SHINSAYAMA 2-CHOME
BillingAddress:
Receiver:Ms Danielle
PostalCode:350107
AddressLine1:#167
AddressLine2:NORTH TOWER HARBOUR CITY


第五步运行结果预期输出:

client返回值=hello








你可能感兴趣的:(REST+SPRING+webservice交互xml数据)