关于基于xfire webservice框架开发webservice的总结

  1. 云栖社区>
  2. 博客列表>
  3. 正文

关于基于xfire webservice框架开发webservice的总结

javaboy2012 2011-02-17 13:40:00 浏览984 评论0

摘要: 关于基于xfire webservice框架开发webservice的总结 基础条件:依赖包和插件 http://repository.codehaus.org/org/codehaus/xfire/xfire-distribution/1.

关于基于xfire webservice框架开发webservice的总结

基础条件:依赖包和插件

http://repository.codehaus.org/org/codehaus/xfire/xfire-distribution/1.2.6/xfire-distribution-1.2.6.zip

开发环境:myeclipse7.5 +tomcat6.0

插件:xfire插件

 

 


包括服务器端的开发和客户端的调用代码的开发

一、 服务器端开发


1.  开发服务接口

package com.mybank.xfire.example;

public interface IBankingService {

 public String transferFunds(String fromAccount, String toAccount,
   double amount, String currency);

}

 

2.  开发服务接口实现类

package com.mybank.xfire.example;

 import java.text.NumberFormat;   
 import java.text.DecimalFormat;   
   
 public class BankingService implements IBankingService {   
   
 //Default constructor.   
    public BankingService(){       
     }   
       
     /** Transfers fund from one account to another.  
    */  
    public String transferFunds(   
        String fromAccount, String toAccount, double amount, String currency){   
          
        String statusMessage = "";   
                          
         //调用业务逻辑执行操作.   
       //建立并返回状态信息.   
        try {   
            NumberFormat formatter = new DecimalFormat("###,###,###,###.00");          
             statusMessage = "COMPLETED: " + currency + " " + formatter.format(amount)+    
             " was successfully transferred from A/C# " + fromAccount + " to A/C# " + toAccount;   
        } catch (Exception e){   
             statusMessage = "BankingService.transferFunds(): EXCEPTION: " + e.toString();   
        }   
         return statusMessage;   
   }   
   
 }

 

3. 接口和实现类的配置

配置文件中加入实现类和接口的配置

配置文件名称为services.xml,其位置为WEB-INF/classes/META-INF/xfire/services.xml
 
<beans xmlns="http://xfire.codehaus.org/config/1.0">        
<service> 
<name>Banking</name>  
<namespace>mybank</namespace>  
<serviceClass>com.mybank.xfire.example.IBankingService</serviceClass>  
<implementationClass>com.mybank.xfire.example.BankingService</implementationClass>  
</service>      
</beans>

注意:<name>Banking</name>    这个Banking

4. web.xml中配置xfire的servlet.


web.xml配置:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
 xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
 
<servlet> 
<servlet-name>XFireServlet</servlet-name>  
<servlet-class>org.codehaus.xfire.transport.http.XFireConfigurableServlet</servlet-class>  
<load-on-startup>0</load-on-startup>  
</servlet>  
<servlet-mapping>  
<servlet-name>XFireServlet</servlet-name>  
<url-pattern>/services/*</url-pattern>  
</servlet-mapping>  
 
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>


注意:servlet配置和url映射

<servlet> 
<servlet-name>XFireServlet</servlet-name>  
<servlet-class>org.codehaus.xfire.transport.http.XFireConfigurableServlet</servlet-class>  
<load-on-startup>0</load-on-startup>  
</servlet>  
<servlet-mapping>  
<servlet-name>XFireServlet</servlet-name>  
<url-pattern>/services/*</url-pattern>  
</servlet-mapping>


5. 发布后测试:

http://192.168.63.187:8080/webservice/services/Banking?wsdl


返回如下:

<?xml version="1.0" encoding="UTF-8"?>
<wsdl:definitions targetNamespace="mybank" xmlns:soapenc12="http://www.w3.org/2003/05/soap-encoding" xmlns:tns="mybank" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap11="http://schemas.xmlsoap.org/soap/envelope/" xmlns:wsdlsoap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:soapenc11="http://schemas.xmlsoap.org/soap/encoding/" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
  <wsdl:types>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" attributeFormDefault="qualified" elementFormDefault="qualified" targetNamespace="mybank">
<xsd:element name="transferFunds">
<xsd:complexType>
<xsd:sequence>
<xsd:element maxOccurs="1" minOccurs="1" name="in0" nillable="true" type="xsd:string"/>
<xsd:element maxOccurs="1" minOccurs="1" name="in1" nillable="true" type="xsd:string"/>
<xsd:element maxOccurs="1" minOccurs="1" name="in2" type="xsd:double"/>
<xsd:element maxOccurs="1" minOccurs="1" name="in3" nillable="true" type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:element name="transferFundsResponse">
<xsd:complexType>
<xsd:sequence>
<xsd:element maxOccurs="1" minOccurs="1" name="out" nillable="true" type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>
  </wsdl:types>
  <wsdl:message name="transferFundsResponse">
    <wsdl:part name="parameters" element="tns:transferFundsResponse">
    </wsdl:part>
  </wsdl:message>
  <wsdl:message name="transferFundsRequest">
    <wsdl:part name="parameters" element="tns:transferFunds">
    </wsdl:part>
  </wsdl:message>
  <wsdl:portType name="BankingPortType">
    <wsdl:operation name="transferFunds">
      <wsdl:input name="transferFundsRequest" message="tns:transferFundsRequest">
    </wsdl:input>
      <wsdl:output name="transferFundsResponse" message="tns:transferFundsResponse">
    </wsdl:output>
    </wsdl:operation>
  </wsdl:portType>
  <wsdl:binding name="BankingHttpBinding" type="tns:BankingPortType">
    <wsdlsoap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
    <wsdl:operation name="transferFunds">
      <wsdlsoap:operation soapAction=""/>
      <wsdl:input name="transferFundsRequest">
        <wsdlsoap:body use="literal"/>
      </wsdl:input>
      <wsdl:output name="transferFundsResponse">
        <wsdlsoap:body use="literal"/>
      </wsdl:output>
    </wsdl:operation>
  </wsdl:binding>
  <wsdl:service name="Banking">
    <wsdl:port name="BankingHttpPort" binding="tns:BankingHttpBinding">
      <wsdlsoap:address location="http://192.168.63.187:8080/webservice/services/Banking"/>
    </wsdl:port>
  </wsdl:service>
</wsdl:definitions>

 

则表示发布成功。

至此,服务器端开发全部完成。

 

二、客户端调用代码的开发


包括以下几种方式


1. 如果能够知道并得到service的类,那么可以在客户端中通过xfier的代理工厂生成service类。然后调用相应的方法。(有服务的代码)


package com.mybank.xfire.example;

import java.net.MalformedURLException;

import org.codehaus.xfire.XFire;
import org.codehaus.xfire.XFireFactory;
import org.codehaus.xfire.client.XFireProxyFactory;
import org.codehaus.xfire.service.Service;
import org.codehaus.xfire.service.binding.ObjectServiceFactory;

public class Client {

 /**
  * @param args
  */
 public static void main(String[] args) {

  Client c=new Client();
  String ret;
  try {
   ret = c.callWebService("111", "222", 1.1d, "aaaaa");
   System.out.println("s="+ret);
  } catch (MalformedURLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }


 }
 
 
 
    public String callWebService(   
             String fromAccount, String toAccount, double amount, String currency)    
              throws MalformedURLException, Exception {   
                 
             //Create a metadata of the service  创建一个service的元数据       
            Service serviceModel = new ObjectServiceFactory().create(IBankingService.class);           
             System.out.println("callSoapServiceLocal(): got service model." );   
            
            //Create a proxy for the deployed service 为XFire获得一个代理工厂对象   
            XFire xfire = XFireFactory.newInstance().getXFire();   
               XFireProxyFactory factory = new XFireProxyFactory(xfire);         
               //得到一个服务的本地代理   
              String serviceUrl = "http://192.168.63.187:8080/webservice/services/Banking";   
                 
             IBankingService client = null;   
              try {   
                   client = (IBankingService) factory.create(serviceModel, serviceUrl);   
              } catch (MalformedURLException e) {   
               System.out.println("WsClient.callWebService(): EXCEPTION: " + e.toString());   
               }       
                         
            //Invoke the service 调用服务 返回状态结果信息   
               String serviceResponse = "";   
              try {    
                 serviceResponse = client.transferFunds(fromAccount, toAccount, amount, currency);   
              } catch (Exception e){   
             System.out.println("WsClient.callWebService(): EXCEPTION: " + e.toString());                    
                 serviceResponse = e.toString();   
             }           
           System.out.println("WsClient.callWebService(): status=" + serviceResponse);                 
        
             //Return the response   
            return serviceResponse;   
        } 

}

 


2. 没有服务的代码,则可以通过xfire插件,自动生成相关的客户端代码

 

插件的地址和安装

利用xfire生成web服务客户端的方法有多种,Eclipse Plugin为XFire的WSDL->Code generator提供了Eclipse支持,它需要Eclipse 3.2和Java 5。这里我们用Eclipse Plugin根据wsdl文件地址生成客户端代码,而我们只需要编写几行代码即可实现调用web服务。下面就是方法步骤:
第一步,安装插件。
        打开Eclipse的Help菜单,选择”Software Updates”,然后再选择”Find and Install.”
        选择"Search for new features to install",然后点击Next
        选择"Create New Remote Site", 在name中输入"XFire",在eclipse update site中输入http://dist.codehaus.org/xfire/update/
        选择OK
        选择Finish。
    注意完成上述操作后,eclipse要下载和安装插件,时间长短要视网速而定,请耐心等待,安装完成时还要重启eclipse。

 


第二步,使用插件。
    首先新建一个java项目XFireProject,然后依次选择菜单File->New->Other ,选择XFire文件夹下的Code generation from WSDL document,打开代码生成向导.


输入wsdl 地址,选择 生成类所在类的包,执行可自动生成一系列文件。其中有XXXXXXclient的类即可调用代码,

package com.yanek.test;

public class Test {

 /**
  * @param args
  */
 public static void main(String[] args) {

  BankingClient bc=new BankingClient();
  System.out.println("xxxyyyy="+bc.getBankingHttpPort().transferFunds("aaa", "bbb", 1.0d, "11111111"));

 }

}


其中BankingClient为自动生成的代码

http://192.168.63.187:8080/webservice/services/Banking?wsdl


需要导入xfire相关jar和apache comm包。

 

 

3. 三,由于service类在很多情况下并不是只有自己开发的。这时候很有可能你没有办法得到service类,但是service发布的wsdl文件是可以得到,xfire可以通过wsdl生成client。这里又包含两种方式,第一,把wsdl下载下来到本地的classpath。通过读取wsdl生成。或者,可以直接通过url来生成。这里说明第二种情况


http://192.168.63.187:8080/webservice/services/Banking?wsdl

 

 

package com.yane.test;

import java.net.HttpURLConnection;
import java.net.URL;

import org.codehaus.xfire.client.Client;

public class Test {

 /**
  * @param args
  */
 public static void main(String[] args) {

  
  Test test=new Test();
  String a=test.transferFunds("111", "222", 1.1d, "aaaaa");
  System.out.println("xxxxxxx="+a);
  
  

 }
 
 
 
    public String transferFunds(   
            String fromAccount, String toAccount, double amount, String currency) 
    {  
        try{  
            String wsdl = "http://192.168.63.187:8080/webservice/services/Banking?wsdl";  
            URL url = new URL(wsdl);  
            HttpURLConnection httpConnection = (HttpURLConnection)url.openConnection();  
            httpConnection.connect();  
            Client client = new Client(httpConnection.getInputStream(),null);             
            Object []results = client.invoke("transferFunds", new Object[]{fromAccount,toAccount,amount,currency});  
            return (String)results[0];  
        }catch(Exception e){  
            throw new RuntimeException(e);  
        }  
    }

 

}

 

其中,
Object []results = client.invoke("transferFunds", new Object[]{fromAccount,toAccount,amount,currency}


中transferFunds为方法名, new Object[]{fromAccount,toAccount,amount,currency} 为对象参数值

 

 

 

 

 

 

 

 

 

 

 

 

 

 

【云栖快讯】阿里云栖开发者沙龙(Java技术专场)火热来袭!快来报名参与吧!  详情请点击

网友评论

javaboy2012
文章331篇 | 关注26
关注
是一款提供了现场可编程门阵列(FPGA)的计算实例,基于阿里云弹性计算框架,用户可以几分钟内... 查看详情
阿里云移动APP解决方案,助力开发者轻松应对移动app中随时可能出现的用户数量的爆发式增长、... 查看详情
基于大数据的移动云服务。帮助App快速集成移动推送的功能,在实现高效、精确、实时的移动推送的... 查看详情
为您提供简单高效、处理能力可弹性伸缩的计算服务,帮助您快速构建更稳定、安全的应用,提升运维效... 查看详情
双12

双12